[C++]LeetCode 9: Palindrome Number(判断整数是否是回文数)

16 篇文章 0 订阅
16 篇文章 1 订阅

Problem:

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.


分析:

回文问题也是经典的面试算法问题。此题是判断int是否是回文,有如下思路:

1、将int转换为string,再判断。

这是最常用的方法,转换后可二分比较,但需要额外空间

2、先将int翻转,再比较两数,翻转方法参见:[C++]LeetCode 7:Reverse Integer(翻转整数)

翻转时考虑了溢出情况,此题中需要另行考虑溢出。

3、直接需要最高和最低位进行比较。(代码采用此法)

看起来有点笨,但是比较通用。

4、期待大家提供更快捷的方法^O^


AC Code(C++):

class Solution {
public:
    //11505 / 11505 test cases passed.
    //Runtime: 124 ms
    
    bool isPalindrome(int x) {
    	if (x < 0)	return false;//负数不为回文
    
    	int leftDiv = 1;//计算左边的最大除数
    	for (int i = x; i > 9; i /= 10){
    		leftDiv *= 10;
    	}
    
    	int rightDiv = 10;
    	while (rightDiv <= leftDiv){//判断是否是回文
    		if (x%rightDiv != x / leftDiv){//非回文
    			return false;
    		}
    		else{
    			x = (x%leftDiv) / rightDiv;
    			//rightDiv *= 10;
    			leftDiv /= 100;
    		}
    	}
    	return true;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值