Algorithm questions daily practice---Day 71: Number of palindromes

Get into the habit of writing together! This is the sixth day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

1. Problem description

Gives you an integer  x , if it  x is a palindrome, return  true ; otherwise, return  false .

A palindrome is an integer that reads the same in positive order (from left to right) and in reverse order (from right to left).

  • For example, 121 is a palindrome,  123 not .

Topic link: Number of palindromes

Second, the subject requirements

Example 1

输入: x = 121
输出: true
复制代码

Example 2

输入: x = -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
复制代码

visit

1.数学思想、回文判断
2.建议用时15~35min
复制代码

3. Problem Analysis

The number of palindromes! Get it up.

25.gif

The number of palindromes is that the result of traversing from front to back corresponds to the result of traversing from back to front. There are many applications that are usually combined with stack, but this problem is relatively simple. We can directly store numbers in arrays.

First, negative numbers directly output false, because the - sign cannot be paired with other numbers.

Second, the data range is up to 10 bits, and a 12-bit sized array is more than enough to store each digit.

After the numbers are stored in the array in order, the first ones are judged in turn, and if they are not equal, false is returned.

Finally, if none of the above error conditions are met, then return true.

Fourth, the encoding implementation

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)//负数返回false
            return false;
        int i,n=0,a[12];//初始化数据
        while(x)//数字存入数组
        {
            a[n++]=x%10;
            x=x/10;
        }
        for(i=0;i<n/2;i++)//首尾依次向内收缩判断
            if(a[i]!=a[n-i-1])//不相等,输出false
                return false;
        return true;//返回true
    }
};
复制代码

5. Test results

2.png

1.png

Guess you like

Origin juejin.im/post/7083287441133535239