C program to find if a number is palindrome or not

不想你离开。 提交于 2020-01-05 09:35:20

问题


I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?

#include <stdio.h>
int main()
{
    int i, x, n, c, j;
    int d=0;
    printf ("enter total digits in number: ");
    scanf ("%d", &i);
    printf ("\nenter number: ");
    scanf ("%d", &n);
    j=n;
    for (x=1; x<=i; x++)
    {
       c= j%10;
       d=c*(10^(i-x))+d;
       j=(j-c)/10;
    }
    if (d==n)
    {
        printf ("\npalindrome");
    }
    else
    {
        printf ("\nnon palindrome");
    }
    return 0;
}

回答1:


^ is the xor operator.

In order to raise power, you need to include math.h and call pow

d = (c * pow(10, i - x)) + d;



回答2:


this algorithm is as simple as human thinking, and it works

#include <stdio.h>


int main() {
    int i=0,n,ok=1;
    char buff[20];


    printf("Enter an integer: ");
    scanf("%d", &n); // i am ommiting error checking

    n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
    if(n<2) return 0;

    i=n/2;
    n--;
    while(i && ok) {
        i--;
        //printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
        ok &= (buff[i]==buff[n-i]);

    }

    printf("%s is %spalindrome\n",buff, ok?"":"not ");
    return 0;
}



回答3:


// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int n, rn, tn;
    printf("Enter an integer: ");
    scanf("%d", &n);    

    // reverse the number by repeatedly extracting last digit, add to the  
    // previously computed partial reverse times 10, and keep dropping  
    // last digit by dividing by 10  
    for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
    if (rn == n) printf("%d is palindrome\n", n);
    else printf("%d is not palindrome\n", n);
}



回答4:


A loop like this might do:

int src;     // user input
int n;       // no of digits
int res = 0;
int tmp;     // copy of src

// .... read the input: n and src ....

tmp = src;
for(int i = 0; i < n; i ++)
{
    int digit = tmp % 10;  // extract the rightmost digit
    tmp /= 10;             // and remove it from source
    res = 10*res + digit;  // apend it to the result
}

// ...and test if(res == src)...


来源:https://stackoverflow.com/questions/33805425/c-program-to-find-if-a-number-is-palindrome-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!