Table of Contents
Title description
Home Backend Development C#.Net Tutorial Three algorithms for finding palindrome numbers in C language

Three algorithms for finding palindrome numbers in C language

Apr 30, 2019 am 09:30 AM
c c++ algorithm

The article shared by the editor today is three algorithms for describing palindrome numbers in C language. It has certain reference value. If you are interested in palindrome numbers in C language, you can take a look. I hope it will be helpful to you.

Title description

  • Note: (These palindrome numbers do not have leading 0)
  • The 1-digit palindrome number has 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 in total;
  • 2-digit palindrome numbers are 11, 22, 33, 44, 55, 66, 77, 88, 99 9 in total;

* I would like to ask: How many n-digit palindromes are there? Please write a recursive function to solve this problem! ! !

  • [Input format] One positive integer per line, representing the number of digits
  • [Output format] One positive integer per line, representing the number of palindrome poems
  • [ Sample input】2
  • 【Sample output】9

Three algorithms for finding palindrome numbers in C language

##Input:

3
Output:
90

Input:

5
Output:
900

** Input:

10
Output:
90000 **

Input:

8
Output:
9000

Input:

1
Output:
10

Idea analysis

    Read this number through a for loop,
  1. Reverse the data through / and % operations, and then compare whether the reversed number is equal to the original number
  2. Three algorithms for finding palindrome numbers in C language

  3. Read this number through a for loop,
  4. take the first number and the last number each time, and compare the two numbers in turn to see if they are equal. , then remove these two numbers until there is one number left (an odd number of digits) or two numbers (an even number of digits)
  5. Three algorithms for finding palindrome numbers in C language

  6. Through

    mathematical relations, directly determine the number of digits and calculate the number of palindromes within this digit;

      For example: 99899
    • can be divided into two halves, take the first half 998, if it is a palindrome number, the second half must correspond to its corresponding position, 998 is a 3-digit word, ** Except for the first bit (excluding leading 0), which number has 9 choices (1-9) for the position corresponding to the second half, the other digits have 10
      choices (0-9) for the corresponding positions* *, for example, the second digit and the penultimate digit (0-9)
    • So the same number of digits can be summarized. If the number of digits is an odd number, the palindrome number is 9*10^(n/2) , note that n/2 is an integer, and the number of digits with an even number is
    • 9
      10^(n/2-1), so the palindrome number of 5-digit numbers is 910*10 =900
    • Note that there are 10 digits (0-9) for 1, which require special processing
Related tutorials:

C Video Tutorial

Code Description

1. 第一种思路:
Copy after login
#include <stdio.h>
#include <math.h>
int reverse(long int i,long int *terminate)        //递归函数求数值的逆序
{
    if (i<=0){              //递归出口
        return 1;       
    }
    else{
        *terminate*=10;     //每次乘10升位数
        *terminate+=i%10;      //加上个位
        reverse(i/10,terminate);        //递归每次规模缩小
    }
    return 1;
}
int main ()
{
    int n;
    scanf ("%d",&n);            //读入一个n,表示n位整数
   long int i;        
    int count=0;
    if (n==1){               //如果等于1,则有10个(0-9都是),特殊处理;
        printf ("10");
        return 0;
    }
    for (i=pow(10,n-1);i<pow(10,n);i++){       //从第一个n位数开始(10^(n-1)),到(10^n)-1
       long int terminate=0;                //定义一个逆序目标数
        reverse(i,&terminate);              //把i和逆序目标数传入
        if (terminate==i){                  //逆序后还和原数相等,则可计数
            count++;
        }
    }
    printf ("%d",count);        //输出个数
    return 0;
}
Copy after login

2. 第二种思路:
Copy after login
#include <stdio.h>
#include <math.h>
int judge(int i,int n)
{
    int first,last;
    if (n<=1){          //规模减小,直到n为1(偶数)或者0
        return 1;

    }
    else{
        first=i/pow(10,n-1);        //头位数字
        last=i%10;                  //末位数字
        if (first!=last){           //头位末尾不一样直接退出
            return 0;
        }
        int tem=pow(10,n-1);        
    judge(i%tem/10,n-2);            //剔除头尾剩下中间,位数减二

    }
}
int main ()
{
    int n;
    scanf("%d",&n);
    if (1==n){
        printf ("10");
        return 0;
    }
    int i;
    int count=0;
   long long  low=pow(10,n-1);      //循环入口
    long long high=pow(10,n);       //循环出口
    for (i=low;i<high;i++){
       if ( judge(i,n)==1){         //判断i是否为回文,计数
           count++;
       }
    }
    printf ("%d",count);
    return 0;
}
Copy after login

3. 第三种思路:
Copy after login
#include <stdio.h>
#include <math.h>
int main (){
    int n;
    scanf ("%d",&n);
    int ji=9*pow(10,n/2),ou=9*pow(10,n/2-1);
    if (n==1){
        printf ("10");
    }
    else if  (n==2){
        printf ("%d",9);
    }
    else if (n%2==1){
        printf ("%d",ji);
    }
    else if (n%2==0){
        printf("%d",ou);
    }
    return 0;
}
Copy after login

The above is the detailed content of Three algorithms for finding palindrome numbers in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Improved detection algorithm: for target detection in high-resolution optical remote sensing images Improved detection algorithm: for target detection in high-resolution optical remote sensing images Jun 06, 2024 pm 12:33 PM

01 Outlook Summary Currently, it is difficult to achieve an appropriate balance between detection efficiency and detection results. We have developed an enhanced YOLOv5 algorithm for target detection in high-resolution optical remote sensing images, using multi-layer feature pyramids, multi-detection head strategies and hybrid attention modules to improve the effect of the target detection network in optical remote sensing images. According to the SIMD data set, the mAP of the new algorithm is 2.2% better than YOLOv5 and 8.48% better than YOLOX, achieving a better balance between detection results and speed. 02 Background & Motivation With the rapid development of remote sensing technology, high-resolution optical remote sensing images have been used to describe many objects on the earth’s surface, including aircraft, cars, buildings, etc. Object detection in the interpretation of remote sensing images

Similarities and Differences between Golang and C++ Similarities and Differences between Golang and C++ Jun 05, 2024 pm 06:12 PM

Golang and C++ are garbage collected and manual memory management programming languages ​​respectively, with different syntax and type systems. Golang implements concurrent programming through Goroutine, and C++ implements it through threads. Golang memory management is simple, and C++ has stronger performance. In practical cases, Golang code is simpler and C++ has obvious performance advantages.

How to implement the Strategy Design Pattern in C++? How to implement the Strategy Design Pattern in C++? Jun 06, 2024 pm 04:16 PM

The steps to implement the strategy pattern in C++ are as follows: define the strategy interface and declare the methods that need to be executed. Create specific strategy classes, implement the interface respectively and provide different algorithms. Use a context class to hold a reference to a concrete strategy class and perform operations through it.

What are the underlying implementation principles of C++ smart pointers? What are the underlying implementation principles of C++ smart pointers? Jun 05, 2024 pm 01:17 PM

C++ smart pointers implement automatic memory management through pointer counting, destructors, and virtual function tables. The pointer count keeps track of the number of references, and when the number of references drops to 0, the destructor releases the original pointer. Virtual function tables enable polymorphism, allowing specific behaviors to be implemented for different types of smart pointers.

How to implement nested exception handling in C++? How to implement nested exception handling in C++? Jun 05, 2024 pm 09:15 PM

Nested exception handling is implemented in C++ through nested try-catch blocks, allowing new exceptions to be raised within the exception handler. The nested try-catch steps are as follows: 1. The outer try-catch block handles all exceptions, including those thrown by the inner exception handler. 2. The inner try-catch block handles specific types of exceptions, and if an out-of-scope exception occurs, control is given to the external exception handler.

Groundbreaking CVM algorithm solves more than 40 years of counting problems! Computer scientist flips coin to figure out unique word for 'Hamlet' Groundbreaking CVM algorithm solves more than 40 years of counting problems! Computer scientist flips coin to figure out unique word for 'Hamlet' Jun 07, 2024 pm 03:44 PM

Counting sounds simple, but in practice it is very difficult. Imagine you are transported to a pristine rainforest to conduct a wildlife census. Whenever you see an animal, take a photo. Digital cameras only record the total number of animals tracked, but you are interested in the number of unique animals, but there is no statistics. So what's the best way to access this unique animal population? At this point, you must be saying, start counting now and finally compare each new species from the photo to the list. However, this common counting method is sometimes not suitable for information amounts up to billions of entries. Computer scientists from the Indian Statistical Institute, UNL, and the National University of Singapore have proposed a new algorithm - CVM. It can approximate the calculation of different items in a long list.

How to copy files using C++? How to copy files using C++? Jun 05, 2024 pm 02:44 PM

How to copy files in C++? Use std::ifstream and std::ofstream streams to read the source file, write to the destination file, and close the stream. 1. Create new streams of source and target files. 2. Check whether the stream is opened successfully. 3. Copy the file data block by block and close the stream to release resources.

How to iterate over a C++ STL container? How to iterate over a C++ STL container? Jun 05, 2024 pm 06:29 PM

To iterate over an STL container, you can use the container's begin() and end() functions to get the iterator range: Vector: Use a for loop to iterate over the iterator range. Linked list: Use the next() member function to traverse the elements of the linked list. Mapping: Get the key-value iterator and use a for loop to traverse it.

See all articles