user2195582
user2195582

Reputation: 57

Extracting indivdual digits from a number.

I am trying to extracting a individual number from a given integer. example from 1234, I want to store 1 , 2 ,3 ,4 in an array.The number of digits might not be same every time. I don't know how to initialize the array for the same.

int number = 1234;

int [] a = new int[];

for(int i =0;i<lengthOfNum;i++){
    a[i] = digitReturn();
}

Upvotes: 0

Views: 94

Answers (4)

Lightsout
Lightsout

Reputation: 3757

int number = 1234;
String num = Integer.toString(number);
int [] a = new int[num.length()];

for(int i = 0; i < num.length(); i++){
    a[i] = Character.getNumericValue(num.charAt(i));
}

First convert number to a String, loop through each char and convert them into an int then storing the value into a.

Upvotes: 0

RizJa
RizJa

Reputation: 2031

You can try the following:

int number = 1234;
int length = Integer.toString(number).length();
int[] a = new int[length];

int index = length - 1;
for (int i = 0; i < length; i++){
    a[i] = number % 10;
    number = number / 10;
    index--;
}

Convert the number to String to get the size and use that value to declare the length of the array and then just loop through it, extracting the last number using modulus and then dividing to get rid of the last digit in the integer.

Upvotes: 4

Andy
Andy

Reputation: 1133

int number = 4567;
String number_string = String.valueOf(number);
char[] chars = number_string.toCharArray();
int[] digits = new int[chars.length];
int i = 0;
for (char c : chars) {
    digits[i] = c - '0';
    i++;
}

Upvotes: 0

DrOverbuild
DrOverbuild

Reputation: 1265

Convert the number into a string, then split the string into an array. After that, convert the characters into integers, like this:

int number = 1234;
List<Integer> digits = ArrayList<Integer>();
String digitsAsString = ("" + number).split("");
for(String digitAsString:digitsAsString){
    digits.add(new Integer(Integer.parseInt(digitAsString));
}

Your array of digits is the list of digits

Upvotes: 0

Related Questions