LeetCode Brush Questions (3)--Palindrome Number

Title description

Determine whether an integer is a palindrome. The palindrome number refers to the same integer in both positive order (from left to right) and reverse order (from right to left).

Example:
Input: 121
Output: true

Input: -121
Output: false

Input: 10
Output: false

Problem-solving ideas

method one:

Convert the input integer into a string, and then perform the reverse position element judgment on the string, loop half of the array size, and return false if it finds inconsistencies, and return true when the loop ends.

Suppose you input 1221, then convert the integer 1221 to a string and store it, and then perform a reverse position comparison on the string 1221. Whether the first element of the array is the same as the last element of the array, the second element of the array is the second to last element of the array Compare whether the two elements are the same, the loop array is half the number of times, and the loop ends are the same, it is the number of palindromes.

Code:

bool huiwenshu(int x,char a[],int n)
{
	if(x<0)
		return false;
	sprintf(a,"%d",x);
	for(int i=0;i<n/2;i++)
	{
		if(a[i]!=a[n-i-1])
		{
			return false;
		}
	}
	return true;
}

int main()
{
	char a[10];
	if(huiwenshu(1001,a,4)==true)
	{
		cout<<"true"<<endl;
	}
	else
	{
		cout<<"false"<<endl;
	}
	return 0;
}

Result:
Insert picture description here
If you enter 1002, the result:
Insert picture description here

Method Two:

Determine whether the value of the integer inversion is consistent with the original value.

In the previous article, I have already explained the method of integer inversion: link: integer inversion.
Directly compare the inverted integer with the original integer. If they are equal, it is a palindrome, and vice versa.

Code:

bool huiwen(int x)
{
	int y=x;//记录输入的整数
	long long r=0;
	if(x<0)//如果数负数
		return false;
	while(x!=0){
		r=r*10+x%10;//计算反转整数
		x/=10;
	}
	if(r!=y)	//判断反转整数和原整数是否一致
		return false;
	else
		return true;
}
int main()
{
	if(huiwen(1001)==true)
	{
		cout<<"true"<<endl;
	}
	else
	{
		cout<<"false"<<endl;
	}
	return 0;
}

Result:
Insert picture description here
If you enter 1002
result:
Insert picture description here

This article mainly explains two methods for judging the number of palindromes. One is to convert an integer to a string, and then compare the elements of the reverse position; the other is to compare the reversed integer with the original integer, both of which can be achieved .

Insert picture description here

Guess you like

Origin blog.csdn.net/baidu_41191295/article/details/112206101