当前位置:网站首页>The number of palindromes in question 9 of C language deduction. Two pointer array traversal method

The number of palindromes in question 9 of C language deduction. Two pointer array traversal method

2022-07-25 00:15:00 Take care of two dogs and never let them go bad

Give you an integer x , If x Is a palindrome integer , return true ; otherwise , return false .

Palindrome number refers to positive order ( From left to right ) Reverse order ( From right to left ) Read all the same integers .

for example ,121 It's palindrome. , and 123 No .
Example 1:
Input :x = 121
Output :true

Example 2:
Input :x = -121
Output :false
explain : Read left to right , by - 121 . Read right to left , by 121 - . So it's not a palindrome number .

Example 3:
Input :x = 10
Output :false
explain : Read right to left , by 01 . So it's not a palindrome number .

source : Power button (LeetCode)
link :https ://leetcode.cn/problems/palindrome-number
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

This question is similar to question 6 and question 7 , Consider three categories : Less than 0、 Normal condition 、 Spillage


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>


int test(int x) 
{
	int left = 0;
	int right = 0;
	int s[20] = { 0 };
	if (x < 0)
		return 0;
	if (x == 0)
		return 1;
	if (x > 0)
	{
		while (x != 0)
		{
			s[right] = x % 10;
			x = x / 10;
			right++;
		}
		right = right - 1;
		while (left <= right)
		{
			if (s[left] == s[right])
			{
				left++;
				right--;
				continue;
			}
			else if (s[left] != s[right])
				return 0;

		}

		if (left == right + 2)
			return 1;
	}
	
}

int main()
{
	int x = 121;
	//printf("%d", x);
	int y = 0;
	y = test(x);
	printf("%d", y);
	return 0;
}


//leetcode Realization 
bool isPalindrome(int x)
{
	int left = 0;
	int right = 0;
	int s[20] = { 0 };
	if (x < 0)
		return false;
	if (x == 0)
		return true;
	if (x > 0)
	{
		while (x != 0)
		{
			s[right] = x % 10;
			x = x / 10;
			right++;
		}
		right = right - 1;
		while (left <= right)
		{
			if (s[left] == s[right])
			{
				left++;
				right--;
				continue;
			}
			else if (s[left] != s[right])
				return false;

		}
		if (left == right + 2)
			return true;
	}
	return true;// The last sentence must add   Report an error without adding   It doesn't work 
}

Because only c++ Boolean type only , So I realized it myself first , Stick to it and switch the return value . Finally, we must pay attention to the final, and there must be a return value , Otherwise, the compiler will not pass , Although it's really useless .

原网站

版权声明
本文为[Take care of two dogs and never let them go bad]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/202/202207201442406164.html