Palindrome Number && Reverse Number

Problem I: 判断数字是不是回文字符串形式

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

 

解决思路

难点在于不使用辅助空间,也就是说不能转成字符串形式再进行判断。

数字操作也就是%和/两种,整体方法如下:

(1)得到最大单位div,如输入的数为1001,则div为1000;

(2)取余和取被除数,然后进行判断,是否相等;

(3)得到去除两边数字的数字,div=div/100,再进入(2),直到输入的数为0为止。

 

程序

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        
        int div = 1;
        while (x / div >= 10) {
            div *= 10;
        }
        
        while (x > 0) {
            int right = x % 10;
            int left = x / div;
            if (left != right) {
                return false;
            }
            x = (x % div) / 10;
            div /= 100;
        }
        
        return true;
    }
}

 

Problem II: 翻转数字

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

解决思路

善用%和/两种符号。

需要注意的是对于越界情况的处理。

 

程序

public class Solution {
    public int reverse(int x) {
        long sum = 0;
        while (x != 0) {
            sum *= 10;
            sum += x % 10;
            x /= 10;
        }
        if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
            return 0;
        }
        return (int)sum;
    }
}

 

posted @ 2015-08-16 13:02  Chapter  阅读(168)  评论(0编辑  收藏  举报