Leetcode Daily Question - "Palindrome Number"

Dear uu of CSDN, hello, today Xiao Yalan is here to brush Likou again. Today’s topic is palindrome number. Next, let’s enter the world of palindrome number.


 

Example 1:

Input: x = 121
Output: true

Example 2:

Input: x = -121
Output: false
Explanation: Read from left to right, it is -121. Read from right to left, it is 121-. Therefore it is not a palindromic number.

Example 3:

Input: x = 10
Output: false
Explanation: Read from right to left, it is 01. Therefore it is not a palindromic number.

 


 Solution 1: Loop

Using a loop method, first, define all required variables as long integers, because they are defined as integers, and some subsequent data integers may not be able to be stored.

Furthermore, according to the example, it can be seen that the palindrome number cannot be negative

Then it can be seen that each digit of a number needs to be obtained, which can be used by the method of /10 and %10

Next, let's take a look at the code:

bool isPalindrome(int x)
{
    long int a=x;
    long int b=0;
    long int res=0;
    //定义一个a用来接受最初x的值(因为x的值经过循环体会改变)
    if(x<0)
    {
        //回文数不可能是负数
        return false;
    }
    while(x>0)
    {
        b=x%10;//得到数的每一位
        x=x/10;//去掉数的最后一位
        res=res*10+b;
        //res用来计算最终值,定义为长整型(测试数据可能太大,int存放不下)
    }
    if(res==a)
    //if判断语句判断res和a是否相等
    {
        return true;
    }
    return false;
}

Alright, this is the end of Xiao Yalan's palindrome today, keep going! ! !

 

Guess you like

Origin blog.csdn.net/weixin_74957752/article/details/130252195
Recommended