Reputation: 47
1. long number = 564;
2. String str = number+"";
3. char[] num = str.toCharArray();
4. number = number - num[0];
/* The value of number is 511 */
I am trying to subtract the first digit of the number from the number using this piece of code.
During debugging, i found out that the value of num[0] was 53. Can anyone explain what am i missing here.
Upvotes: 0
Views: 148
Reputation: 1927
It just feels wrong to convert a number to a string, extract the first char, convert back to number and subtract. Why don't you extract the first digit while working with numbers directly. Something like this would do:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
int firstDigit = (int) (number / Math.pow(10, digits -1));
number = number - firstDigit;
System.out.println(number);
If you want to get all digits:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
for (int digit = digits - 1; digit >= 0; digit--) {
int currentDigit = (int) (number / Math.pow(10, digit)) % 10;
System.out.println(currentDigit);
}
Upvotes: 0
Reputation: 271
When you are using the binary operator "-" the smaller datatype, in this case char, is promoted to long which returns the ASCII value of num[0] ('5') which is 53. To get the actual face value of num[0] convert it to String and parse it to Long as Sweeper has pointed out.
Upvotes: 1
Reputation: 271945
I would suggest you to change your fourth line to this:
number = number - Long.parseLong(Character.toString(num[0]));
Basically, what is happening here is that I first convert the char
(num[0]
) to a string, then parsed the string to a long
.
ALternatively, you don't even need to convert the string to a char array! Use charAt()
to get the char:
number = number - Long.parseLong(Character.toString(str.charAt(0)));
Upvotes: 1