找出一个数字是否以 2 开头的更快方法? [英] Faster way to find out if a number starts with 2?
本文介绍了找出一个数字是否以 2 开头的更快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中 - 查找给定整数是否以数字 2 开头而无需将数字转换为字符串的更快方法是什么?
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'
推荐答案
如果您想避免将其转换为字符串,您可以继续除以 10 以找到最高有效数字:
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;
}
我不知道这是否会比 Husman 的 log/pow 方法更快.
I don't know whether this would be faster than Husman's log/pow approach.
这篇关于找出一个数字是否以 2 开头的更快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文