Sean
Sean

Reputation: 1313

Extracting digits of int in Java

So if I have an inputted integer:

int num_1 = 128

How would I be able to parse through the number and obtain a 1, 2 and 8, and assign them to different variables?

Thanks!

Upvotes: 11

Views: 48447

Answers (15)

Shay Dratler
Shay Dratler

Reputation: 11

I think you can use this solution :

int getDigit(int num,int location){
    return BigDecimal.valueOf(num/Math.pow(10,position)).intValue() %10;
  }

in this solution what will happen is the following you are sending a number due to usage of Math that returns a double we need to convet it again to integer we use the BigDecimal. the main idea or logic is the Math.pow with the position it returns the prefix of number and then the module chops the other end. you can check it with the following Sample:

    System.out.println(getDigit(123456,1));
    System.out.println(getDigit(123456,2));
    System.out.println(getDigit(123456,3));
    System.out.println(getDigit(123456,4));
    System.out.println(getDigit(123456,5));
    System.out.println(getDigit(123456,10) );  

Enjoy

Upvotes: 1

Saikat
Saikat

Reputation: 16780

Java 8 Solution

String.valueOf(n).chars().forEach(i -> System.out.println((char) i))

where n=the integer

Upvotes: 0

user3626925
user3626925

Reputation: 71

To know where the digits are coming from I'd go:

return (x/10/10) + (x%10) + (x/10)%10;

Upvotes: 1

Oleg Mikhailov
Oleg Mikhailov

Reputation: 6081

If you don't appreciate the idea of String conversion and want to iterate using normal order, try this:

int n = 123456789;
int digits = (int) Math.log10(n);
for (int i = (int) Math.pow(10, digits); i > 0; i /= 10) {
    System.out.println(n / i);
    n %= i;
}

Output would be

1
2
3
4
5
6
7
8
9 

Upvotes: 1

Levi Schneider
Levi Schneider

Reputation: 43

Now if you are trying to single out numbers in a string among letters then this should take care of that.

String string = "Th1s 1s n0t a number";

int newNum = Integer.parseInt(string.replaceAll("[\\D]", ""));
return newNum;

This should return 110

Also, here is a link to a stack discussion that I found really helpful. Get int from String, also containing letters, in Java

Upvotes: 1

BullyWiiPlaza
BullyWiiPlaza

Reputation: 19195

This code returns the nibble at the given index. If you want to get all digits, you can call this method with all indices of your number. It does not work on the hexadecimal representation of a number but on the decimal one.

public static int getNibble(int number, int nibbleIndex)
{
    int nibble = 0;

    while (nibbleIndex >= 0)
    {
        int division = number / 10;
        nibble = number - division * 10;
        number = division;

        nibbleIndex--;
    }

    return nibble;
}

Upvotes: 1

bruhhhhh
bruhhhhh

Reputation: 121

Here is a purely mathematical way of doing so:

// Returns digit at pos
static int digitAt(int input, int pos){     
    int i =(int) (input%(Math.pow(10, pos)));
    int j = (int) (i/Math.pow(10, pos-1));
    return Math.abs(j); // abs handles negative input
}

For example if input = 1234 and pos = 2, then i is 34. We divide the 34 by 10 and round off to get a 3.

Not that pretty, but works!

Upvotes: 2

Ashwin Parmar
Ashwin Parmar

Reputation: 3045

Collect all the digits in the Array and use futher

import java.lang.Integer;
import java.lang.String;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class Test
{

    public static void main(String[] args) {
        Integer num =  12345;
        Integer[] digits = getDigits(num.toString());
        System.out.println(Arrays.toString(digits));
    }

    public static Integer[] getDigits(String number) {
        List<Integer> digits = new ArrayList<Integer>();
        for(int i = 0; i < number.length(); i++) {
            int j = Character.digit(number.charAt(i), 10);
            digits.add(j);
        }       
        return digits.toArray(new Integer[]{});
    }
}

Output should be

[1, 2, 3, 4, 5]

Upvotes: 2

Nir Alfasi
Nir Alfasi

Reputation: 53525

The answer that Thilo wrote is good but incomplete, you start by doing:

char[] digitsAsChars = String.valueOf(num_1).toCharArray();

and then:

int[] digits = new int[charNums.length];
for(int i=0; i<charNums.length; i++){
   digits[i] = charNums[i]-48;//convert char to int
}

now digits holds the digits of the number as an int array

Upvotes: 7

Ashwin Parmar
Ashwin Parmar

Reputation: 3045

int num = 128;
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);
}

Output:

digit: 1
digit: 2
digit: 8

Upvotes: 4

Omry Yadan
Omry Yadan

Reputation: 33646

the inefficient way to do this would be to convert the integer to a string and iterate on the string characters.

the more efficient way would be something like:

int n = 128;
while (n > 0) {
  int d = n / 10;
  int k = n - d * 10;
  n = d;
  System.out.println(k);
}

Upvotes: 20

david
david

Reputation: 3218

String str = Integer.toString(num_1);

You can obtain 1,2,8 from this str

Upvotes: 1

upog
upog

Reputation: 5531

try

while (num_1> 0){
            int digit = num_1%10;
            num_1 = num_1/10;
            System.out.println(digit);
        }

Upvotes: 5

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

Here's one way:

String digits = Integer.toString(num_1);
int digit1 = Character.digit(digits.charAt(0), 10);
int digit2 = Character.digit(digits.charAt(1), 10);
int digit3 = Character.digit(digits.charAt(2), 10);

Of course, if the integer has more than three digits, using a loop would be more practical:

String sDigits = Integer.toString(num_1);
char[] cDigits = sDigits.toCharArray();
int[] digits = new int[cDigits.length];

for (int i = 0; i < cDigits.length; i++)
    digits[i] = Character.digit(cDigits[i], 10);

With the above code in place, it's easy to extract the digits from the array:

int digit1 = digits[0];
int digit2 = digits[1];
int digit3 = digits[2];

Upvotes: 3

Thilo
Thilo

Reputation: 262514

Turn it into a String and go character by character for the digits:

char[] digits = String.valueOf(num_1).toCharArray();

Upvotes: 3

Related Questions