从Java中的数字中删除数字
如何删除整数的第一个数字?
我的输入是一个整数(例如i = 123456789)。
然后我想删除第一个数字,以便我等于23456789。
试试这个
n = n % (int) Math.pow(10, (int) Math.log10(n));
这是一种方法:
- 将其转换为
String
- 不带第一个“数字”的子串
- 将其转换为
int
码:
public static void main(String[] args) { int x = 123456789; String x_str = Integer.toString(x); int new_x = Integer.parseInt(x_str.substring(1)); System.out.println(new_x); }
输出:
23456789
注意:这可以在一行中完成
int x = 123456789; int new_x = Integer.parseInt(Integer.toString(x).substring(1));
编辑:
要处理否定的情况,请检查数字是正数还是整数:
int new_x = Integer.parseInt(x > 0 ? Integer.toString(x).substring(1) : Integer.toString(x).substring(2));
如果要避免字符串转换,可以找到高位并减去它。
public static void main(String[] args) { int x = 123456789; System.out.println("x = " + x); int hi = x, n = 0; while (hi > 9) { hi /= 10; ++n; } for (int i = 0; i < n; i++) hi *= 10; x -= hi; System.out.println("x with high digit removed = " + x); }
这是一行的纯数字解决方案:
i %= (int) Math.pow(10, (int) Math.log10(i));
替代方法:
int stripLeading(int i) { if(i > 0) { return i - (int)Math.pow(10, (int)Math.log10(i)); } else if(i > 0) { return i + (int)Math.pow(10, (int)Math.log(-i+1)); } else { return 0; } }
我想我记得这个没有字符串的版本…虽然我完全赞同@Christian,但我会怎么做…
注意:正如@Darren Gilroy所指出的那样,必须考虑负面和零点,我的function不能这样做。
当然%
也是更好的解决方案。
public static void main (String [] argv) { final int x = 123456789; int newX = x; /* How many digits are there? */ final double originalLog = Math.floor (Math.log10 (x)); /* Let's subtract 10 to that power until the number is smaller */ final int getRidOf = (int)Math.pow (10, originalLog); while (originalLog == Math.floor (Math.log10 (newX))) { newX -= getRidOf; } System.out.println (newX); }
分析尝试不佳:
在for
循环中循环上述函数而不使用println
进行20,000,000,000次重复:
real 0m9.943s user 0m9.890s sys 0m0.028s
与Christian更容易理解和完美function的版本相同,但只有200,000,000次重复(因为我很懒,厌倦了等待):
real 0m18.581s user 0m17.972s sys 0m0.574s
因此,有人可能会认为构造String对象可能会将其减慢大约200倍,但这并不是一个非常精细的分析设置。
如果你想使用更简单的方法而不使用String
,那么这是我的简单方法:
- 计算整数中的位数。
- 将
int
除以10^n
。n
是位数。 - 获得结果的绝对值。 //如果是( – )ve数字。
例如
int i = 123456789; int n = getDigitCount(i); int r = Math.abs(i / (int)Math.pow(10,n)); //r stores result.
你需要这个方法:
int getDigitCount(int num) { int c = 0; while(num > 0){ num/=10; c++; } return c; }