I want to create a loop in Java that mathematically takes a variable, say one million, then reduces it by the steps detailed in the program & table below.
package com.sbs.test.maths;
import org.testng.annotations.Test;
public class Maths {
@Test
public void test() {
int i = 1000000;
System.out.println( i );
while( i > 1 ) {
i = reduce( i );
System.out.println( i );
}
}
private int reduce( int value ) {
if ( value > 1 && value <= 10 ) value -= 1;
else if ( value > 10 && value <= 100 ) value -= 10;
else if ( value > 100 && value <= 1000 ) value -= 100;
else if ( value > 1000 && value <= 10000 ) value -= 1000;
else if ( value > 10000 && value <= 100000 ) value -= 10000;
else if ( value > 100000 && value <= 1000000 ) value -= 100000;
else if ( value > 1000000 && value <= 10000000 ) value -= 1000000;
else if ( value > 10000000 && value <= 100000000 ) value -= 10000000;
return value;
}
}
i.e.
value reduce-by result
1000000 - 100000 = 900000
900000 - 100000 = 800000
...
200000 - 100000 = 100000
100000 - 10000 = 90000
90000 - 10000 = 80000
...
20000 - 10000 = 10000
10000 - 1000 = 9000
9000 - 1000 = 8000
...
2000 - 1000 = 1000
1000 - 100 = 900
900 - 100 = 800
...
200 - 100 = 100
100 - 10 = 90
90 - 10 = 80
Can this be done without a nasty if cascade for detecting if the number is 100, 1000, 10000, 100000 or more?
I found a javascript example that I almost got to work in Java, but it wasn’t working for all variations. I ran the program below, but as you will see, it gets stuck at the point where we need to lose a zero on the end of the reduction.
System.out.println( "----------------------------------------------" );
for ( int i = 1000000; i > 0; i -= (int) Math.pow( 10, Math.floor( Math.log( i ) / Math.log(10) ) ) ) {
System.out.println( i );
}
The output:
1000000
900000
800000
700000
600000
500000
400000
300000
200000
100000
Unfortunately maths is not my strong point, so any help on this is much appreciated.
Thanks!
In case you still need it.