简体   繁体   中英

Integer => Digit, and vice versa

is there a way in Java to convert an Integer to single digits, and vice versa. Like this:

So I have the number 345. I want to break it down to 3, 4 and 5 - three seperate numbers.

I have the numbers 3, 4 and 5. I want to put them together to make 345?

You would have to use a combination of mod and divide .

Here is a short method -

public void integerToSingleDigit(int number){
 while (number > 0) {
    System.out.print(number % 10 + " "); // get u the right most single digit
    number = number / 10; // remove the single digit from the right
 }

}

Well you can easily convert it to a character array, and go from there:

char[] parts = Integer.toString(value).toCharArray();
int[] digits = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
  digits[i] = parts[i] - '0';
}

(You don't really need the char array here - you could just use the string and use length() and charAt() instead of length and the indexer - but I find this clearer.)

Then to reassemble, just do the reverse - create a char[] from the digits (by adding '0' to each), then create a string from the char[] , then use Integer.parseInt .

The simplest way would be the following

for (char c : String.valueOf(numberToSplit).toCharArray()) {
  int digit = Character.getNumericValue(c);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM