How in Java do you return the first digit of an integer.?
i.e.
345
Returns an int of 3.
How in Java do you return the first digit of an integer.?
i.e.
345
Returns an int of 3.
The easiest way would be to use String.valueOf(Math.abs((long)x)).charAt(0)
- that will give it you as a char
1. To get that as an integer value, you could just subtract '0' (as in Unicode, '0' to '9' are contiguous).
It's somewhat wasteful, of course. An alternative would just be to take the absolute value, then loop round dividing by 10 until the number is in the range 0-9. If this is homework, that's the answer I'd give. However, I'm not going to provide the code for it because I think it might be homework. However, if you provide comments and edit your answer to explain how you're doing and what problems you're running into, we may be able to help.
1One sticky point to note is that the absolute value of Integer.MIN_VALUE
can't be represented as an int
- so you may should first convert to a long
, then use Math.abs
, then do arithmetic. That's why there's a cast there.
Homework Hint: Convert it to a string and and return the first character.
public static int firstDigit(int n) {
while (n < -9 || 9 < n) n /= 10;
return Math.abs(n);
}
Should handle negative numbers pretty well, too. Will return a negative first digit in that case.
Yet another way:
public int firstDigit(int x) {
if (x == 0) return 0;
x = Math.abs(x);
return (int) Math.floor(x / Math.pow(10, Math.floor(Math.log10(x))));
}
public static int getFirstDigit(int i) {
while (Math.abs(i) >= 10 ) {
i = i / 10;
}
return Math.abs(i);
}
int main(void) {
int num = 3421;
while (num*num + 10 - num*(1 + num) <= 0) {
num *= (num - 0.9*num)/num;
}
std::cout << num << std::endl;
}
Fastest way would be :
The missing recursive solution:
int getFirstInt(int input) {
if (input > 0 ? input < 10 : input > -10) {
return input > 0 ? input : -input;
}
return getFirstInt(input / 10);
}
I wouldn't use the ternary operator in real life but - isn't it kind of beautiful? ;)
This is Groovy, but it should be easy to convert to Java:
int firstNum(int x) {
a = Math.abs(x)
sig = Math.floor(Math.log10(a))
return a / Math.pow(10, sig)
}
Results:
groovy> println(firstNum(345))
3groovy> println(firstNum(3452))
3groovy> println(firstNum(-112))
1groovy> println(firstNum(9999))
9groovy> println(firstNum(Integer.MAX_VALUE))
2groovy> println(firstNum(Integer.MIN_VALUE + 1))
2
Adjusting my previous answer to handle Integer.MIN_VALUE and keep the cast to long out of the interation:
public static int getFirstDigit(int i) {
if (Math.abs((long)i) >= 10 ) {
i = i / 10;
while (Math.abs(i) >= 10 ) {
i = i / 10;
}
}
return Math.abs(i);
}