I think I remember a line-free version ... although I totally agree with @Christian how I do it ...
NOTE. As Darden Gilroy noted, you need to consider negatives and zero selectively, and my function cannot do this.
Of course, % also a better solution.
public static void main (String [] argv) { final int x = 123456789; int newX = x; final double originalLog = Math.floor (Math.log10 (x)); final int getRidOf = (int)Math.pow (10, originalLog); while (originalLog == Math.floor (Math.log10 (newX))) { newX -= getRidOf; } System.out.println (newX); }
Bad profiling attempt:
Completing the specified function without println for 20,000,000,000 repetitions in a for loop:
real 0m9.943s user 0m9.890s sys 0m0.028s
The same thing with the Christian much simpler and more understandable version, but only 200,000,000 repetitions (because I'm lazy and tired of waiting):
real 0m18.581s user 0m17.972s sys 0m0.574s
So, it can be argued that building String objects probably slows it down by about 200 ×, but this is not a very finely tuned profiling setting.
BRFennPocock
source share