3
3
import java .io .BufferedReader ;
4
4
import java .io .FileReader ;
5
5
import java .io .IOException ;
6
+ import java .math .BigInteger ;
6
7
7
8
/**
8
9
* Created by IntelliJ IDEA.
13
14
*/
14
15
public class ReverseAndAdd {
15
16
16
- public static long getReverse (long n ) {
17
- return Long . valueOf (new StringBuilder ().append (n ).reverse ().toString ());
17
+ public static BigInteger getReverse (BigInteger n ) {
18
+ return new BigInteger (new StringBuilder ().append (n ).reverse ().toString ());
18
19
}
19
20
20
- public static boolean isPalindrome (long n ) {
21
- return n == getReverse (n );
21
+ public static boolean isPalindrome (BigInteger n ) {
22
+ return n . compareTo ( getReverse (n )) == 0 ;
22
23
}
23
24
24
- public static boolean isNegative (long n ) {
25
- return n < 0 ;
25
+ public static boolean isNegative (BigInteger n ) {
26
+ return n . compareTo ( new BigInteger ( "0" )) == - 1 ;
26
27
}
27
28
28
- public static long [] reverseAddAndCheck (String n ) {
29
- long additions = 1 ;
30
- long original = Long . valueOf (n );
29
+ public static BigInteger [] reverseAddAndCheck (String n ) {
30
+ BigInteger additions = new BigInteger ( "1" ) ;
31
+ BigInteger original = new BigInteger (n );
31
32
32
33
boolean isNegative = isNegative (original );
33
- if (isNegative ) original = - original ;
34
+ if (isNegative ) original = original . multiply ( new BigInteger ( "-1" )) ;
34
35
35
- long reverse ;
36
+ BigInteger reverse ;
36
37
37
- while (!isPalindrome (original + (reverse = getReverse (original )))) {
38
- original += reverse ;
39
- additions ++ ;
38
+ while (!isPalindrome (original . add (reverse = getReverse (original )))) {
39
+ original = original . add ( reverse ) ;
40
+ additions = additions . add ( new BigInteger ( "1" )) ;
40
41
}
41
42
42
- original += reverse ;
43
- if (isNegative ) original = - original ;
43
+ original = original . add ( reverse ) ;
44
+ if (isNegative ) original = original . multiply ( new BigInteger ( "-1" )) ;
44
45
45
- return new long []{additions , original };
46
+ return new BigInteger []{additions , original };
46
47
}
47
48
48
49
public static void readFile (String filePath ) {
@@ -52,8 +53,8 @@ public static void readFile(String filePath) {
52
53
String line ;
53
54
54
55
while ((line = br .readLine ()) != null ) {
55
- long [] result = reverseAddAndCheck (line );
56
- System .out .println (result [0 ] + " " + result [1 ]);
56
+ BigInteger [] result = reverseAddAndCheck (line );
57
+ System .out .println (result [0 ]. toString () + " " + result [1 ]. toString () );
57
58
}
58
59
59
60
} catch (IOException e ) {
0 commit comments