LeetCode (30) Palindrome Number (回文数字)

来源:互联网 发布:画树状图软件 编辑:程序博客网 时间:2024/05/17 10:04

题目描述

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

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.
—— 将数字转换为字符串,我们做过判断字符串是否为回文的题目的,但是这里会用到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?
—— 将数字逆转,判断逆转前后是否相同,但是这会出现overflow的问题(没有做过”Reverse Integer”的题目,也不是很清楚为什么会溢出。)

本题要求判断数字是否为回文,并要求不能利用额外的内存空间。本题可以利用类似字符串的回文判断使用两个指针进行判断。当然对一个数字我们无法从前后移动两个指针,指向不同的数字为,这里我们可以通过数学运算,每次获得数字的最高位和最低位的数值。

首先获得数字的位数,依次通过除以 10*ditalNumber 和 对10取余分别获得最高位和最低位的数字,判断两数字是否相等。需要注意的是每次得到最高位数需要除去的数字大小的变化。总体来说,代码比较简单。

class Solution {public:    bool isPalindrome(int x) {        if (x < 0) return false;        if (x < 10) return true;        int count = 0;        int t = x;        while (t)        {            count++;            t = t / 10;        }        int highNum = pow(10, count - 1);        while (highNum > 1)        {            int high = x / highNum;            int low = x % 10;            if (high != low)    return false;            x = x - highNum * high;            highNum /= 100;            x = x / 10;        }        return true;    }};
0 0
原创粉丝点击