LeetCode练习-数组-palindrome-number

33 篇文章 0 订阅
8 篇文章 0 订阅


题目描述

Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.


思路1:先算出数字的位数,然后循环比较对应位数字是否相同,若相同,则继续比较;若不同,则返回false。

思路2:反转数字(注意溢出问题)


代码:

#include<iostream>
#include<math.h>
using namespace std;

bool isPalindrome(int x);
bool isPalindrome_2(int x);
int main(){
	cout << isPalindrome(100801) << endl;
	return 0;
}
bool isPalindrome(int x){
	if(x < 0)
		return false;
	int count = 1;
	int a = x;
	while(a/10 != 0){//计算数字位数
		++count;
		a = a/10;
	}
	int tenH = pow(10, count - 1);//初始化tenH,用来计算高位数字
	int tenL = int(pow(10, 1));//初始化tenL,用来计算低位数字
	int i;
	for(i = 1; i <= count/2; ++i){
		//int h = x / pow(10, count - i);
		int h = x / tenH;
		tenH = tenH / 10;//更新tenH
		if(h >= 10)
			h = h % 10;
		
		//int l = x % int(pow(10, i));
		//l = l / int(pow(10, i-1));
		int l = x % tenL;
		l = l / (tenL / 10);
		tenL = tenL * 10;//更新tenL
		//cout << "h: " << h << " l: " << l << endl;//测试输出

		if(h != l)//比较对应位
			return false;
	}
	return true;
}
bool isPalindrome_2(int x) {
        int res=0;
    int tmp=x;
    if(x<0)
        return false;
    while(tmp)
    {
        res=res*10+tmp%10;//此公式可自动处理末尾为0而逆反带来的溢出问题
        tmp/=10;
    }
    if(res==x)
        return true;
    else
        return false;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值