Faster way to find out if a number starts with 2?
java, numbers, performance
Solution
If you wanted to avoid converting it to a string, you could just keep dividing by 10 to find the most significant digit:
int getMostSignificantDigit(int x)
{
// Need to handle Integer.MIN_VALUE "specially" as the absolute value can't
// represented. We can hard-code the fact that it starts with 2 :)
x = x == Integer.MIN_VALUE ? 2 : Math.abs(x);
while (x >= 10)
{
x = x / 10;
}
return x;
}
I don't know whether this would be faster than Husman's log/pow approach.
Problem
In Java - what is the faster way to find if the given integer number is starting with the digit 2 without having to convert the number into a string? ``` String.valueOf(number).charAt(0) == '2' ```