Palindrome Numbers [Blue Bridge Cup]

Title link: Palindrome Number [Blue Bridge Cup]
Time limit: 1 Sec Memory limit: 256 MB

Title description:
Observation numbers: 12321 and 123321 have a common feature, whether they are read from left to right or from right to left, they are the same.
Such numbers are called: palindrome numbers.
This question requires you to find some 5-digit or 6-digit decimal numbers. Meet the following requirements:
the sum of the digits of the number is equal to the input integer.

Input:
a positive integer n (10<n<100), which represents the sum of digits required to be met.

Output:
Several lines, each line contains a 5-digit or 6-digit integer that meets the requirements. The numbers are arranged in ascending order.
If the conditions are not met, output: -1

Sample input
45
Sample output
99999

Question: Determine whether a number (10000<=num<=999999) is a palindrome and the sum of the digits is equal to the entered number.
Idea: Just traverse the judgment.

How to judge?
Insert picture description here

On the code:

int palindrome(int x)
{
    
    
    int px=0,xx=x; // px:x倒序的结果 xx:记录x
    int ans=0; //ans:数位和结果
    while(x)
    {
    
    
        px = px*10+x%10;
        ans += x%10;
        x /= 10;
    }
    if(px==xx) // x为回文数
        return ans;  // 返回数位和
    else
        return -1;
}

Use px to store the result of the reverse order, ans store the digital sum, and determine whether it is a palindrome (use px and xx to compare), if it is to return the digital sum directly, then compare the returned digital sum with the input number, if it is equal, then Prove that it meets the requirements and output it.

You must understand the smart one?
Insert picture description here

Complete code:

#include<bits/stdc++.h>
using namespace std;
int palindrome(int x)
{
    
    
    int px=0,xx=x; // px:x倒序的结果 xx:记录x
    int ans=0; //ans:数位和结果
    while(x)
    {
    
    
        px = px*10+x%10;
        ans += x%10;
        x /= 10;
    }
    if(px==xx) // x为回文数
        return ans;  // 返回数位和
    else
        return -1;
}
int main()
{
    
    
    int n;
    while(cin>>n)
    {
    
    
        int flag=0; // 设置一个标记,标记是非有符合条件的回文数
        for(int i=10000; i<=999999; i++)
        {
    
    
            if(palindrome(i)==n)  // i为回文数并且数位和等于输入的n
            {
    
    
                flag=1;
                cout<<i<<endl;
            }
        }
        if(flag==0)
            cout<<-1<<endl;
    }
    return 0;
}

Don't forget to like it after reading the cuties, thank you for your support!
Insert picture description here

Come on!

Work together!

Keafmd

Guess you like

Origin blog.csdn.net/weixin_43883917/article/details/108736534