小白笔记----------------------leetcode(9. Palindrome Number)

来源:互联网 发布:处理器调度算法实现 编辑:程序博客网 时间:2024/05/18 06:49

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?

这里要求不能用多余空间,那就仅仅依靠/ 和%这两个运算就能够成功地将这个题解出来了

代码:

public class Solution {    public boolean isPalindrome(int x) {        if(x < 0){            return false;        }else if(x < 10){            return true;        }        int i = 1;        int s = x;        int r = x;        int reverse = 0,t;        boolean flag;        while(x >= 10){            x = x/10;            i++;        }        int j = 0;        while(i > 1 && j < i){            reverse = reverse * 10 + s%10;            s = s/10;            j++;        }        if(reverse == r){            flag = true;        }else{            flag = false;        }        return flag;            }}


0 0