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

来源:互联网 发布:淘宝客推广怎么样 编辑:程序博客网 时间:2024/05/16 13:38

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;            }};


0 0
原创粉丝点击