在Java中 - 查找给定整数是否以数字2开头而不需要将数字转换为字符串的更快方法是什么?
String.valueOf(number).charAt(0) == '2'
如果你想避免将其转换为字符串,你可以继续除以 10 来找到最高有效数字:
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 方法更快。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)