Reputation: 11
I am attempting to store the digits of a 4-digit number into an array, but it ends up being reversed: 1234
is stored as [4,3,2,1]
in the array.
int[] nums = new int[4];
for (int i = 0; i < length; i++) {
nums[i] = input % 10;
input /= 10;
System.out.print(nums[i]);
}
Upvotes: 0
Views: 60
Reputation: 4197
Another option is to change array index:
nums[nums.length - i - 1] = input % 10;
Upvotes: 0
Reputation: 4252
You just need to traverse the array in a reverse order, since number % 10 will give you the digit in the ten's position.
eg: if number 1234 , number % 10 => 4 which should be stored at the end of your array viz nums[3]
for (int i = nums.length - 1; i >= 0; i--) {
nums[i] = input % 10;
input /= 10;
System.out.print(nums[i]);
}
Upvotes: 2
Reputation: 191738
input % 10;
will return the tens position of the number first, so just loop backwards over the array positions.
for (int i = nums.length - 1; i >= 0; i--) {
You could also use an ArrayList and check while(input > 0)
to do any length number.
Upvotes: 2