File tree Expand file tree Collapse file tree 2 files changed +77
-0
lines changed Expand file tree Collapse file tree 2 files changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Reverse digits of an integer.
3+ * <p>
4+ * Example1: x = 123, return 321
5+ * Example2: x = -123, return -321
6+ * <p>
7+ * Have you thought about this?
8+ * Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
9+ * <p>
10+ * If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
11+ * Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of
12+ * 1000000003 overflows. How should you handle such cases?
13+ * For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
14+ * <p>
15+ * Note:
16+ * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer
17+ * overflows.
18+ * <p>
19+ * Created by drfish on 25/06/2017.
20+ */
21+ public class _007ReverseInteger {
22+ public int reverse (int x ) {
23+ int result = 0 ;
24+ while (x != 0 ) {
25+ int tail = x % 10 ;
26+ int temp = result * 10 + tail ;
27+ if ((temp - tail ) / 10 != result ) {
28+ return 0 ;
29+ }
30+ result = temp ;
31+ x /= 10 ;
32+ }
33+ return result ;
34+ }
35+
36+ public static void main (String [] args ) {
37+ _007ReverseInteger solution = new _007ReverseInteger ();
38+ assert 321 == solution .reverse (123 );
39+ assert -321 == solution .reverse (-123 );
40+ assert 0 == solution .reverse (2147483647 );
41+ }
42+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * Determine whether an integer is a palindrome. Do this without extra space.
3+ * <p>
4+ * Some hints:
5+ * Could negative integers be palindromes? (ie, -1)
6+ * <p>
7+ * If you are thinking of converting the integer to string, note the restriction of using extra space.
8+ * <p>
9+ * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that
10+ * the reversed integer might overflow. How would you handle such case?
11+ * <p>
12+ * There is a more generic way of solving this problem.
13+ * <p>
14+ * Created by drfish on 25/06/2017.
15+ */
16+ public class _009PalindromeNumber {
17+ public boolean isPalindrome (int x ) {
18+ if (x < 0 || (x != 0 && x % 10 == 0 )) {
19+ return false ;
20+ }
21+ int reverse = 0 ;
22+ while (x > reverse ) {
23+ reverse = reverse * 10 + x % 10 ;
24+ x /= 10 ;
25+ }
26+ return (x == reverse || x == reverse / 10 );
27+ }
28+
29+ public static void main (String [] args ) {
30+ _009PalindromeNumber solution = new _009PalindromeNumber ();
31+ assert solution .isPalindrome (12321 );
32+ assert solution .isPalindrome (123321 );
33+ assert !solution .isPalindrome (-121 );
34+ }
35+ }
You can’t perform that action at this time.
0 commit comments