您的位置:首页 > 编程语言

leetcode:9 Palindrome Number-每日编程第二十八题

2015-12-15 21:45 267 查看
Palindrome Number

Total
Accepted: 95160 Total
Submissions: 317694 Difficulty: Easy

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

思路:

1).使用while(x/10>base),而不是while(x>base){ base*=10}; base/=10; 是为了防止base溢出。

2).因为不允许使用额外空间,不能简单的将其转换为数组形式,对比首尾是否相等,所以,就只能轮流求出首尾数字值,比较其是否相等,不相等,则返回false。

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0){
            return false;
        }
        int base = 1;
        while(x/10>=base){
            base*=10;
        }
        int left,right;
        while(base>=10){
            left=x/base;
            x-=left*base;
            right=x%10;
            x/=10;
            if(left!=right){
                return false;
            }
            base/=100;
        }
        return true;
        
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: