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;
}

发布了9 篇原创文章 · 获赞 15 · 访问量 3029

猜你喜欢

转载自blog.csdn.net/u010259177/article/details/79833536