首页 > 其他 > 详细

LeetCode #9 Palindrome Number (E)

时间:2015-10-06 06:54:06      阅读:259      评论:0      收藏:0      [点我收藏+]

[Problem]

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

 

[Analysis]

这题不能转换为String来做因为要求constant space。只要依次比较头尾两个数字就可以了。

 

[Solution]

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        
        // initialize base
        int base = 1;
        while (x/base >= 10) {
            base *= 10;
        }
        
        while (x != 0) {
            int leftMost = x/base;
            int rightMost = x % 10;
            if (leftMost != rightMost) {
                return false;
            } else {
                x = (x % base) / 10;
                base /= 100;
            }
        }
        
        return true;
    }
}

 

LeetCode #9 Palindrome Number (E)

原文:http://www.cnblogs.com/zhangqieyi/p/4856615.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!