I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.
How can I get it in Java?
To do this, you will use the % (mod) operator.
int number; // = some int
while (number > 0) {
print( number % 10);
number = number / 10;
}
The mod operator will give you the remainder of doing int division on a number.
So,
10012 % 10 = 2
Because:
10012 / 10 = 1001, remainder 2
Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.
Code to print the numbers in the correct order:
int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
stack.push( number % 10 );
number = number / 10;
}
while (!stack.isEmpty()) {
print(stack.pop());
}
Convert it to String and use String#toCharArray() or String#split().
String number = String.valueOf(someInt);
char[] digits1 = number.toCharArray();
// or:
String[] digits2 = number.split("(?<=.)");
In case you're already on Java 8 and you happen to want to do some aggregate operations on it afterwards, consider using String#chars() to get an IntStream out of it.
IntStream chars = number.chars();
How about this?
public static void printDigits(int num) {
if(num / 10 > 0) {
printDigits(num / 10);
}
System.out.printf("%d ", num % 10);
}
or instead of printing to the console, we can collect it in an array of integers and then print the array:
public static void main(String[] args) {
Integer[] digits = getDigits(12345);
System.out.println(Arrays.toString(digits));
}
public static Integer[] getDigits(int num) {
List<Integer> digits = new ArrayList<Integer>();
collectDigits(num, digits);
return digits.toArray(new Integer[]{});
}
private static void collectDigits(int num, List<Integer> digits) {
if(num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}
If you would like to maintain the order of the digits from least significant (index[0]) to most significant (index[n]), the following updated getDigits() is what you need:
/**
* split an integer into its individual digits
* NOTE: digits order is maintained - i.e. Least significant digit is at index[0]
* #param num positive integer
* #return array of digits
*/
public static Integer[] getDigits(int num) {
if (num < 0) { return new Integer[0]; }
List<Integer> digits = new ArrayList<Integer>();
collectDigits(num, digits);
Collections.reverse(digits);
return digits.toArray(new Integer[]{});
}
I haven't seen anybody use this method, but it worked for me and is short and sweet:
int num = 5542;
String number = String.valueOf(num);
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
System.out.println("digit: " + j);
}
This will output:
digit: 5
digit: 5
digit: 4
digit: 2
I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:
int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();
To be clear:
You use String.valueOf(number) to convert int to String, then chars() method to get an IntStream (each char from your string is now an Ascii number), then you need to run map() method to get a numeric values of the Ascii number. At the end you use toArray() method to change your stream into an int[] array.
I see all the answer are ugly and not very clean.
I suggest you use a little bit of recursion to solve your problem. This post is very old, but it might be helpful to future coders.
public static void recursion(int number) {
if(number > 0) {
recursion(number/10);
System.out.printf("%d ", (number%10));
}
}
Output:
Input: 12345
Output: 1 2 3 4 5
simple solution
public static void main(String[] args) {
int v = 12345;
while (v > 0){
System.out.println(v % 10);
v /= 10;
}
}
// could be any num this is a randomly generated one
int num = (int) (Math.random() * 1000);
// this will return each number to a int variable
int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;
// you could continue this pattern for 4,5,6 digit numbers
// dont need to print you could then use the new int values man other ways
System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);
Since I don't see a method on this question which uses Java 8, I'll throw this in. Assuming that you're starting with a String and want to get a List<Integer>, then you can stream the elements like so.
List<Integer> digits = digitsInString.chars()
.map(Character::getNumericValue)
.boxed()
.collect(Collectors.toList());
This gets the characters in the String as a IntStream, maps those integer representations of characters to a numeric value, boxes them, and then collects them into a list.
Java 9 introduced a new Stream.iterate method which can be used to generate a stream and stop at a certain condition. This can be used to get all the digits in the number, using the modulo approach.
int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
Note that this will get the digits in reverse order, but that can be solved either by looping through the array backwards (sadly reversing an array is not that simple), or by creating another stream:
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
or
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length - i]).toArray();
As an example, this code:
int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
Will print:
[0, 0, 4, 3, 2, 1]
[1, 2, 3, 4, 0, 0]
Easier way I think is to convert the number to string and use substring to extract and then convert to integer.
Something like this:
int digits1 =Integer.parseInt( String.valueOf(201432014).substring(0,4));
System.out.println("digits are: "+digits1);
ouput is
2014
I wrote a program that demonstrates how to separate the digits of an integer using a more simple and understandable approach that does not involve arrays, recursions, and all that fancy schmancy. Here is my code:
int year = sc.nextInt(), temp = year, count = 0;
while (temp>0)
{
count++;
temp = temp / 10;
}
double num = Math.pow(10, count-1);
int i = (int)num;
for (;i>0;i/=10)
{
System.out.println(year/i%10);
}
Suppose your input is the integer 123, the resulting output will be as follows:
1
2
3
Here is my answer, I did it for myself and I hope it's simple enough for those who don't want to use the String approach or need a more math-y solution:
public static void reverseNumber2(int number) {
int residual=0;
residual=number%10;
System.out.println(residual);
while (residual!=number) {
number=(number-residual)/10;
residual=number%10;
System.out.println(residual);
}
}
So I just get the units, print them out, substract them from the number, then divide that number by 10 - which is always without any floating stuff, since units are gone, repeat.
Java 8 solution to get digits as int[] from an integer that you have as a String:
int[] digits = intAsString.chars().map(i -> i - '0').toArray();
neither chars() nor codePoints() — the other lambda
String number = Integer.toString( 1100 );
IntStream.range( 0, number.length() ).map( i -> Character.digit( number.codePointAt( i ), 10 ) ).toArray(); // [1, 1, 0, 0]
Why don't you do:
String number = String.valueOf(input);
char[] digits = number.toCharArray();
Try this one.
const check = (num) => {
let temp = num
let result = []
while(temp > 0){
let a = temp%10;
result.push(a);
temp = (temp-a)/10;
}
return result;
}
check(98) //[ 8, 9 ]
public int[] getDigitsOfANumber(int number) {
String numStr = String.valueOf(number);
int retArr[] = new int[numStr.length()];
for (int i = 0; i < numStr.length(); i++) {
char c = numStr.charAt(i);
int digit = c;
int zero = (char) '0';
retArr[i] = digit - zero;
}
return retArr;
}
Integer.toString(1100) gives you the integer as a string. Integer.toString(1100).getBytes() to get an array of bytes of the individual digits.
Edit:
You can convert the character digits into numeric digits, thus:
String string = Integer.toString(1234);
int[] digits = new int[string.length()];
for(int i = 0; i<string.length(); ++i){
digits[i] = Integer.parseInt(string.substring(i, i+1));
}
System.out.println("digits:" + Arrays.toString(digits));
This uses the modulo 10 method to figure out each digit in a number greater than 0, then this will reverse the order of the array. This is assuming you are not using "0" as a starting digit.
This is modified to take in user input.
This array is originally inserted backwards, so I had to use the Collections.reverse() call to put it back into the user's order.
Scanner scanNumber = new Scanner(System.in);
int userNum = scanNumber.nextInt(); // user's number
// divides each digit into its own element within an array
List<Integer> checkUserNum = new ArrayList<Integer>();
while(userNum > 0) {
checkUserNum.add(userNum % 10);
userNum /= 10;
}
Collections.reverse(checkUserNum); // reverses the order of the array
System.out.print(checkUserNum);
Just to build on the subject, here's how to confirm that the number is a palindromic integer in Java:
public static boolean isPalindrome(int input) {
List<Integer> intArr = new ArrayList();
int procInt = input;
int i = 0;
while(procInt > 0) {
intArr.add(procInt%10);
procInt = procInt/10;
i++;
}
int y = 0;
int tmp = 0;
int count = 0;
for(int j:intArr) {
if(j == 0 && count == 0) {
break;
}
tmp = j + (tmp*10);
count++;
}
if(input != tmp)
return false;
return true;
}
I'm sure I can simplify this algo further. Yet, this is where I am. And it has worked under all of my test cases.
I hope this helps someone.
int number = 12344444; // or it Could be any valid number
int temp = 0;
int divider = 1;
for(int i =1; i< String.valueOf(number).length();i++)
{
divider = divider * 10;
}
while (divider >0) {
temp = number / divider;
number = number % divider;
System.out.print(temp +" ");
divider = divider/10;
}
Try this:
int num= 4321
int first = num % 10;
int second = ( num - first ) % 100 / 10;
int third = ( num - first - second ) % 1000 / 100;
int fourth = ( num - first - second - third ) % 10000 / 1000;
You will get first = 1, second = 2, third = 3 and fourth = 4 ....
Something like this will return the char[]:
public static char[] getTheDigits(int value){
String str = "";
int number = value;
int digit = 0;
while(number>0){
digit = number%10;
str = str + digit;
System.out.println("Digit:" + digit);
number = number/10;
}
return str.toCharArray();
}
As a noob, my answer would be:
String number = String.valueOf(ScannerObjectName.nextInt());
int[] digits = new int[number.length()];
for (int i = 0 ; i < number.length() ; i++)
int[i] = Integer.parseInt(digits.substring(i,i+1))
Now all the digits are contained in the "digits" array.
if digit is meant to be a Character
String numstr = Integer.toString( 123 );
Pattern.compile( "" ).splitAsStream( numstr ).map(
s -> s.charAt( 0 ) ).toArray( Character[]::new ); // [1, 2, 3]
and the following works correctly
numstr = "000123" gets [0, 0, 0, 1, 2, 3]
numstr = "-123" gets [-, 1, 2, 3]
A .NET solution using LINQ.
List<int> numbers = number.ToString().Select(x => x - 48).ToList();
I think this will be the most useful way to get digits:
public int[] getDigitsOf(int num)
{
int digitCount = Integer.toString(num).length();
if (num < 0)
digitCount--;
int[] result = new int[digitCount];
while (digitCount-- >0) {
result[digitCount] = num % 10;
num /= 10;
}
return result;
}
Then you can get digits in a simple way:
int number = 12345;
int[] digits = getDigitsOf(number);
for (int i = 0; i < digits.length; i++) {
System.out.println(digits[i]);
}
or more simply:
int number = 12345;
for (int i = 0; i < getDigitsOf(number).length; i++) {
System.out.println( getDigitsOf(number)[i] );
}
Notice the last method calls getDigitsOf method too much time. So it will be slower. You should create an int array and then call the getDigitsOf method once, just like in second code block.
In the following code, you can reverse to process. This code puts all digits together to make the number:
public int digitsToInt(int[] digits)
{
int digitCount = digits.length;
int result = 0;
for (int i = 0; i < digitCount; i++) {
result = result * 10;
result += digits[i];
}
return result;
}
Both methods I have provided works for negative numbers too.
see bellow my proposal with comments
int size=i.toString().length(); // the length of the integer (i) we need to split;
ArrayList<Integer> li = new ArrayList<Integer>(); // an ArrayList in whcih to store the resulting digits
Boolean b=true; // control variable for the loop in which we will reatrive step by step the digits
String number="1"; // here we will add the leading zero depending on the size of i
int temp; // the resulting digit will be kept by this temp variable
for (int j=0; j<size; j++){
number=number.concat("0");
}
Integer multi = Integer.valueOf(number); // the variable used for dividing step by step the number we received
while(b){
multi=multi/10;
temp=i/(multi);
li.add(temp);
i=i%(multi);
if(i==0){
b=false;
}
}
for(Integer in: li){
System.out.print(in.intValue()+ " ");
}
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num=sc.nextInt();
System.out.println("Enter a number (-1 to end):"+num);
int result=0;
int i=0;
while(true)
{
int n=num%10;
if(n==-1){
break;
}
i++;
System.out.println("Digit"+i+" = "+n);
result=result*10+n;
num=num/10;
if(num==0)
{
break;
}
}
}
}
Is there any good way to search through a floats first four numbers and return every number separately with int[]?
Example: the float 23,51 becomes the integer array, array[0]=2, array[1]=3, array[2]=5 and last array[3]=1
My code:
public void printNumber(float number){
String string = String.valueOf(number);
while(!numbers.isEmpty()){
numbers.remove(0);
}
for(int i = 0; i < string.length(); i++) {
int j = Character.digit(string.charAt(i), 10);
this.number = new Number(j);
numbers.add(this.number);
System.out.println("digit: " + j);
}
}
I should mention that Number is a class that only returns a different picture based on the number the constructor is given and ofcourse the number itself.
numbers is an ArrayList
Convert float to String using fixed-point format, then go through its characters one-by-one, and ignore the decimal point.
If the number could also be negative, you need to pay attention to the sign in the String output:
float v = 23.51F;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
char[] d = df.format(v).toCharArray();
int count = 0;
for (int i = 0 ; i != d.length ; i++) {
if (Character.isDigit(d[i])) {
count++;
}
}
int[] res = new int[count];
int pos = 0;
for (int i = 0 ; i != d.length ; i++) {
if (Character.isDigit(d[i])) {
res[pos++] = Character.digit(d[i], 10);
}
}
Demo.
Important: Be aware that floats are inherently imprecise, so you may get a "stray" digit or two. For example, your example produces
[2 3 5 1 0 0 0 0 2 3]
with 2 and 3 at the end.
You can convert the float to String with 4 decimal places using String.format method, and then get each character to int array
float floatValue = 12.34567f;
String str = String.format("%.4f", floatValue);
// remove the minus, dot, or comma (used in some countries)
str = str.replaceAll("[-|.|,]", "");
int [] nums = new int[str.length()];
for (int i=0; i<str.length(); i++) {
nums [i] = str.charAt(i) - '0';
}
Here is DEMO
As for the code last line, decimal value of '0' char (which is 48) is subtracted from a decimal value of digit char, and the result is integer value of that digit (as specified in below table):
Java 8 flavored solution:
float number = -7.54f;
int[] digits = String.format("%.3f", number)
.chars()
.filter(Character::isDigit)
.limit(4L)
.map(Character::getNumericValue)
.toArray();
System.out.println(Arrays.toString(digits)); //=> [7, 5, 4, 0]
Use the static method Float.toString() to convert your float to a String.
Then go through each char and use Integer.parseInt() to get back to an int.
public void printNumber(float number){
String string = Float.toString(number);
for(int i = 0; i < string.length(); i++) {
int j = Integer.parseInt(string.charAt(i));
this.number = new Number(j);
numbers.add(this.number);
System.out.println("digit: " + j);
}
}
Another option
public static void main(String[] args) {
float number = 23.51f;
String strNumber = String.valueOf(number).replaceAll("\\D", "");
int[] arrNumber = new int[strNumber.length()];
for (int pos = 0; pos < strNumber.length(); ++pos) {
arrNumber[pos] = Integer.valueOf(String.valueOf(strNumber.charAt(pos)));
System.out.println(arrNumber[pos]);
}
}
is there a function in java that works like SUBSTRING function but for integers. Like for example the user's input is 456789, I want to break it into two part and put them into different variable. and divide them. for example,
user's input : 456789
the first 3 numbers will be in variable A.
the last 3 numbers will be in variable B.
pass = A/B;
can someone help me how can I do this,
thanks.
Use integer division and the modulus operator:
int input = 456789;
int a = input / 1000;
int b = input % 1000;
Here is a mathematical based implementation for positive and negative integers (probably can be optimized):
public static void main(String[] args) {
System.out.println(substring(2, 0, 1)); // prints "2"
System.out.println(substring(2523, 2, 2)); // prints "23"
System.out.println(substring(-1000, 0, 2)); // prints "-1"
System.out.println(substring(-1234, 0, 4)); // prints "-123"
System.out.println(substring(-1010, 2, 1)); // prints "0"
System.out.println(substring(-10034, 3, 2)); // prints "3"
System.out.println(substring(-10034, 2, 4)); // prints "34"
}
public static int substring(int input, int startingPoint, int length) {
if (startingPoint < 0 || length < 1 || startingPoint + length > size(input)) {
throw new IndexOutOfBoundsException();
}
if (input < 0 && startingPoint == 0 && length < 2) {
throw new IndexOutOfBoundsException("'-' can not be returned without a digit");
}
input /= (int) Math.pow(10, size(input) - length - startingPoint); // shift from end by division
input = input % (int) Math.pow(10, length); // shift from start by division remainder
if (input < 0 && startingPoint > 0) {
input = Math.abs(input); // update sign for negative input
}
return input;
}
private static int size(int input) {
int size = 1;
while (input / 10 != 0) {
size++;
input /= 10;
}
return input < 0 ? ++size : size; // '-'sign is a part of size
}
Splitting a "number" is not what you want to do. You want to split the NUMERAL, which is the string representing a quantity (number). You can split the numeral just like any other literal (string): don't parse the user's input and use substring. If you want to make sure the literal is an actual numeral, parse it to see if an exception is thrown. If not, you have a numeral. But don't hold on to the integers, keep the strings instead.
Here you go:
You give the method a number, start, and end indexes.
public static void main(String[] args) {
System.out.println(getPartOfInt(93934934, 3, 7));`
}
public static int getPartOfInt(int number, int start, int end){
Integer i = new Integer(number);
char[] chars = i.toString().toCharArray();
String str = "";
for(int j = start; j < end && j < chars.length; j++){
str += chars[j];
}
return Integer.parseInt(str);
}
OR:
public static int getPartOfInt(int number, int start, int end){
String str = new Integer(number).toString();
return Integer.parseInt(str.substring(start, Math.min(end, str.length())));
}
You could also first convert the number to String, like so:
int num = 456789;
String strNum = String.valueOf(num);
String part1 = strNum.substring(0, strNum.length() / 2 - 1);
String part2 = strNum.substring(strNum.length() / 2);
Then, you could convert it back to int, like so:
int part1Num = Integer.parseInt(part1);
int part2Num = Integer.parseInt(part2);
Now you can do all the arithmetic you want with those two int's.
#DeanLeitersdorf Here's the function ( #clcto s solution)
int subinteger(int input, int from, int size)
{
while (input > pow(10, size + from) - 1)
input /= 10;
return input % (int)pow(10, size);
}
This is a c++ solution but i hope that you can convert it to Java easily
So this probably would be easy if done like this
public static [] nums(int j)
{
int num = 12345;
int[]thenums = [5];
for(int i=0; i<5; i++)
{
thenums[4-i] = num%10;
num = num/10;
}
return the nums
}
i get {1,2,3,4,5}
but for some reason if the number starts with a 0 then it does not work
how to make this work if the number were
int num = 02141;
thanks
EDIT: Doh... I'd completely forgotten about octal literals. That explains why the value is showing up differently. (02141 is treated as an octal literal; it's not the same value as 2141.)
However, it sounds like the OP wants to "remember" the number of leading zeroes in a number. There's no way of doing that as an integer, because it's just remembering a value. What's the difference between seeing "3" birds and seeing "0000003" birds?
If you have a number representation where the leading zeroes are important, you're not just talking about an integer quantity, which is all that an int represents.
Where are you getting your input from? It sounds like you should just be maintaining it as a string from the start.
If you always want 5 digits, that's easy to do - and your current code should do it (when amended to actually compile) - something like this:
public class Test
{
public static void main(String[] args)
{
int[] digits = getDigits(123);
for (int digit : digits)
{
System.out.print(digit); // Prints 00123
}
}
public static int[] getDigits(int value)
{
int[] ret = new int[5];
for (int i = 4; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
return ret;
}
}
Now that's hard-coded to return 5 digits. If you don't know the number of digits at compile-time, but you will know it at execution time, you could pass it into the method:
public static int[] getDigits(int value, int size)
{
int[] ret = new int[size];
for (int i = size - 1; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
// Perhaps throw an exception here if value is not 0? That would indicate
// we haven't captured the complete number
return ret;
}
What happens in your code is that 02141 is not the same as 2141; the first is octal (equivalent to 1121 decimal), while the second is 2141 decimal.
The relevant part of the Java Language Specification is JLS 3.10.1, specifically the grammar productions for DecimalNumeral and OctalNumeral.