Before start there are several things,you should be noticed:
1.The differences between 'for ( int i = (int) Math.pow( 2 , 32 ) - 1; i < (int) Math.pow( 2 , 32 ); i++)'
and 'for ( int i = (int) Math.pow( 2 , 32 ) - 1; i < Math.pow( 2 , 32 ); i++)'.The former is right.
Because the later can not get the right comparing result,which performs a situation that 2147483647 is followed
by -2147483648.
2.The method 'Math.pow(double a,double b)' returns a result of double.
3.The losing of precise of results will happen,if you transfer double into long.
The right way to transfer from duble to long is that the number of double wraps with Double and uses the method longValue().
Here is code:
I remix two methods,which are achieving the same goal,to testify the accuracy of each other.And i modify some places in two methods to achieve reversing 2147483647 and -2147483648.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class ReverseInteger {
public long reverse1(int x) {
long a = 0;
int b = 0;
if ( x >= 0 ) {
b = ( x + "" ).length();
}
else {
b = ( x + "" ).length() - 1;
}
if ( ( x > new Double( Math.pow( 2 , 31 ) - 1 ).longValue()||
( x < new Double( ( -1 ) * Math.pow( 2 , 31 ) ).longValue() )) ) {
return 0;
}
while ( x!= 0 ) {
for ( int i = 0; i < b; i++ ) {
int a1 = x % 10;
x = (int)( x - a1 ) / 10;
a += a1 * Math.pow( 10 , b-i-1 );
}
}
return a;
}
public long reverse2(int x)
{
long res = 0;
while (x != 0) {
long temp = res * 10 + x % 10;
x = x / 10;
if (temp / 10 != res)
{
System.out.println("res = 0 <== "+x);
res = 0;
break;
}
res = temp;
}
return res;
}
public static void main(String[] args) throws FileNotFoundException {
System.out.println((long)Math.pow( 2 , 31 ) - 1);
System.out.println(new ReverseInteger().reverse1(2147483647)+"reverse1 2147483647");
System.out.println(new ReverseInteger().reverse2(2147483645)+"reverse2");
File file = new File("C:/User/a.txt");
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
for ( int i = (int) Math.pow( 2 , 31 ) - 1; i < (int) Math.pow( 2 , 31 ); i++) {
if ( new ReverseInteger().reverse1(i) != new ReverseInteger().reverse2(i) ) {
try {
bw.write(i+"----------------------------------------------------finished!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
try {
bw.write(" "+i+" ");
bw.write("finished");
bw.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("finished!");
}
}