satnam
satnam

Reputation: 1425

Java - how to break a integer into its digits

newbie here. I'm practicing Data Structures and Algorithms for interviews. I'm stuck at this situation, where basically it requires to break down an integer (Eg. 615) to its digits (Eg. 6, 1, 5). I did find a solution online, however I feel there has to be a better and simpler way to do this?

Here is the solution that I found -

 int total = sum1 + sum2; //This is the number we want to split
 Integer totalInt = new Integer(total);
 String strSum = totalInt.toString();

 for (int i = 0; i < strSum.length(); i++) {
  String subChar = strSum.substring(i, i + 1);
  int nodeData = Integer.valueOf(subChar);
  newList.append(new Node(nodeData)); //irrelevant in context of question
 }

Upvotes: 1

Views: 3049

Answers (5)

A human being
A human being

Reputation: 1220

Try this

int total = 123; //This is the number we want to split
Integer totalInt = new Integer(total);
String strSum = totalInt.toString();
String nums[] = strSum.split("");

// First element will be empty
// Changed loop initial value i to 0 from 1
for( int i = 0; i < nums.length; i++ ) {
    System.out.println(nums[i]);
    // Or if you want int from it, then
    System.out.println(Integer.parseInt(nums[i]));
}

Output :

1
2
3

Upvotes: 1

felipecrp
felipecrp

Reputation: 1069

You can use toCharArray():

char[] digits = strSum.toCharArray();

Then, convert it to int[]:

int[] numbers = new int[digits.length]; 

for (int i = 0; i < numbers.length; i++) {
    numbers[i] = digits[i] - '0';
}

Upvotes: 1

sprinter
sprinter

Reputation: 27966

A way you can make your method multi-purpose is by making it a Spliterator. That means it can produce a stream of Integer that can be used for any purpose: sum them, add them to a list, whatever.

If you're not familiar with spliterators, here's an example:

public class Digitiser implements Spliterators.OfInt {
    private int currentValue;
    private final int base;
    public Digitiser(int value, int base) {
        currentValue = value;
        this.base = base;
    }
    public boolean tryAdvance(IntConsumer action) {
        if (currentValue == 0) {
            return false;
        } else {
            int digit = value % base;
            value /= base;
            action.accept(digit);
            return true;
        }
    }
    public static IntStream stream(int value, int base) {
        return StreamSupport.intStream(new Digitiser(value, base), false);
}

Now you've got a general purpose digitiser that can be used to do all sorts of things:

Digitiser.stream(13242, 10).sum();
Digitiser.stream(42234, 2).collect(Collectors.toList());

Upvotes: 2

MinecraftShamrock
MinecraftShamrock

Reputation: 3574

This one works with any base:

int input = yourInput;
final int base = 10; //could be anything
final ArrayList<Integer> result = new ArrayList<>();
while(input != 0) {
    result.add(input % (base));
    input = input / base;
}

If you need the digits ordered so that the most significant one is the first, you could use a Stack instead of a List for the result variable.

Upvotes: 3

ruakh
ruakh

Reputation: 183331

It depends exactly what you're trying to do with the broken-up digits; but for an example, here is a way to add up the digits of a positive integer:

int sumOfDigits = 0;
while (n > 0) {
    final int lastDigit = n % 10;    // remainder of n divided by 10
    sumOfDigits += lastDigit;
    n /= 10;                         // divide by 10, to drop the last digit
}

Upvotes: 1

Related Questions