LeetCode之9_Palindrome Number

题目原文

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


题意分析:

不使用额外空间,判断给定的一个整数是否为回文整数。

如果只是求回文数字很简单,题目的难度在于不使用额外的空间(此处认为除了传入参数,临时变量的使用为额外空间,运行过程中产生的栈对象不考虑)

此处判断首尾是否相同,并去除相同数字后继续比较的做法,特殊情况为去除首位后下一位为零,此时需要判断末位是否有同样多个零,并将其去除。


代码:

//不使用额外的空间,求一个整数的回文数

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


class Solution {
public:
	bool isPalindrome(int x) {
		
		if (x<0)
		{
			return false;
		}

		if ( x/10 == 0)
		{
			//个位数直接返回成功
			return true;
		}

		
		while (x/10 != 0)
		{
			if (x%10 == (x/(int)pow(10,(double)(int)log10((double)x))))
			{
				//首尾位相同,消除后继续判断

				//消除最后一位
				x = x/10;

				//消除第一位
				//判断消除第一位后是否开头数字为0

				if ((int)log10((double)x)-(int)log10((double)(x%(int)pow(10,(double)(int)log10((double)x)))) > 1)
				{
					//如果开头第一位为0,判断0的个数,并确认结尾的相同个数也是0
					//否则不对称
					/*int ttemp = (int)log10((double)x)-(int)log10((double)(x%(int)pow(10,(double)(int)log10((double)x)))) -1;
					int temp = x % (int)pow(10,(double)(int)log10((double)x)-(int)log10((double)(x%(int)pow(10,(double)(int)log10((double)x))))-1);*/
					if (x % (int)pow(10,(double)(int)log10((double)x)-(int)log10((double)(x%(int)pow(10,(double)(int)log10((double)x)))) -1) == 0)
					{
						//若开头和结尾的相同个数都是零,则首尾同时去掉相同的个数
						x = x / (int)pow(10,(double)(int)log10((double)x)-(int)log10((double)(x%(int)pow(10,(double)(int)log10((double)x))))-1);
						x = (x%(int)pow(10,(double)(int)log10((double)x)));
					}
					else
						return false;
				}
				else
					x = (x%(int)pow(10,(double)(int)log10((double)x)));
			}
			else
				return false;
		}

		return true;
	}
};


//int main()
//{
//	int x = 1000001;
//	bool isReal = Solution().isPalindrome(x);
//	cout<<isReal<<endl;
//	system("pause");
//	int n = log10((double)x);
//	cout<<pow(10,(double)(int)log10((double)x))<<endl;
//	int left = x / pow(10,log10((double)x));
//	cout<<left<<endl;
//	system("pause");
//}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值