LeetCode Palindrome Number回文数判断

采用两种方法实现,其实时间复杂度都一样;

第一种直接比较对位的数;

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

bool isPalindrome(int x) {
	if (x < 0) return false;
		int x_len = 1;
		while (x /int (pow(10,x_len))) {//求数据长度
			x_len++;
		}
		int cycle = x_len / 2;
		for (int val = 0; val <cycle; ++val) {
			if ((x % 10) != x / int(pow(10, x_len - 1))) //判断前后数字是否相同
				return false;
			x_len -= 2;
				x = (x / 10) % (int(pow(10, x_len)));//跟新数据,去除头尾	
			
		}
		return true;	
}
int main() {
	int x;
	cin >> x;
	cout<< isPalindrome(x) << endl;
	system("pause");
	return 0;
}

第二种,转换成string,再比较,这种防止溢出。

#include<string>
#include<iostream>
using namespace std;

bool isPalindrome(int x) {
	string a=to_string( x);
	int length =a.length();
	for (int i = 0; i <= length / 2; i++) {
		if (a[i] != a[length - i - 1]) return false;	
	}
	return true;
	}
	

int main()
{
	int x;
	cin >> x;
	cout << isPalindrome(x) << endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值