在Java中,如何返回整数的第一个数字?
即
345
返回一个值为3的整数。
发布于 2010-01-13 03:51:20
还有另一种方式:
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))));
}
发布于 2010-01-13 03:46:20
public static int firstDigit(int n) {
while (n < -9 || 9 < n) n /= 10;
return Math.abs(n);
}
应该也能很好地处理负数。在这种情况下,将返回负的第一个数字。
发布于 2010-01-13 05:47:54
忽略负值会导致:
(""+345).charAt(0);
https://stackoverflow.com/questions/2051817
复制相似问题