How to get separate digits of an int number in Java

4 Answers

0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        int n = 923047;
         
        String sn = String.valueOf(n);
         
        char[] digits = sn.toCharArray();
         
        System.out.println(Arrays.toString(digits));
    }
}




/*
run:

[9, 2, 3, 0, 4, 7]

*/

 



answered Sep 12, 2016 by avibootz
edited Nov 14, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        int n = 923047;
         
        String sn = String.valueOf(n);

        char[] digits = sn.toCharArray();
          
        for (int i = 0; i < digits.length; i++)
             System.out.println(digits[i]);
    }
}




/*
run:

9
2
3
0
4
7

*/

 



answered Sep 12, 2016 by avibootz
edited Nov 14, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        int n = 9801725;
 
        while (n > 0) {
            System.out.println(n % 10);
            n = n / 10;
        }
    }
}




/*
run:

5
2
7
1
0
8
9

*/

 



answered Nov 14, 2023 by avibootz
0 votes
import java.util.LinkedList; 

public class MyClass {
    public static void main(String args[]) {
        int n = 9801725;
 
        LinkedList<Integer> ll = new LinkedList<Integer>();
        
        while (n > 0) {
            ll.push(n % 10 );
            n = n / 10;
        }
 
        while (!ll.isEmpty()) {
            System.out.println(ll.pop());
        }
    }
}




/*
run:

9
8
0
1
7
2
5

*/

 



answered Nov 14, 2023 by avibootz

Related questions

2 answers 162 views
1 answer 175 views
2 answers 162 views
3 answers 246 views
2 answers 115 views
1 answer 112 views
...