[LeetCode] Palindrome Number

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.

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?

There is a more generic way of solving this problem.

 

每次,取出数的最高位和最低位比较,这里设置一个base为10^n,用来取出数的最高位,每次循环除以100,因为每次数会消去2位。

复制代码
 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (x < 0)
 7             return false;
 8         if (x == 0)
 9             return true;
10             
11         int base = 1;
12         while(x / base >= 10)
13             base *= 10;
14             
15         while(x)
16         {
17             int leftDigit = x / base;
18             int rightDigit = x % 10;
19             if (leftDigit != rightDigit)
20                 return false;
21             
22             x -= base * leftDigit;
23             base /= 100;
24             x /= 10;
25         }
26         
27         return true;
28     }
29 };
复制代码

 

posted @   chkkch  阅读(9538)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示