0

This code don't give me the right answer and i couldn't find the mistake. How can i fix the code?

Scenario: First it determines number's number of digits and then palindromes the number.

#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
    int number=42321,j=0,dig,temp;
    long long pal= 0LL;

    temp=number;     
    while(temp>0)
    {
          temp/=10;
          j++;
    }

    while (number>0)
    {          
          dig=number%10;
          pal+=dig*(int)pow(10,j);
          number/=10;
          j--;  
    }

    printf("%d",pal);
    getch();   
}
Dorukcan Kişin
  • 1,121
  • 2
  • 14
  • 29

2 Answers2

3

In

while(temp>0)
{
      temp/=10;
      j++;
}

you are computing the number of digits that number has, that's one more than the exponent of the highest power of ten not exceeding number. You need to decrement j after that.

But using pow() is not the best way, far better is to construct the reversed number incrementally:

while(temp > 0)
{
    pal = 10*pal + temp%10;
    temp /= 10;
}
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
2

You defined pal as long long. Afterwards you lied to the compiler telling it you would be passing a value of type int but sending pal: a value of type long long

    printf("%d",pal); /* WRONG */

Don't do that. Use the proper conversion specifier

    printf("%lld", pal); /* preferred */

or cast the value to the proper type

    printf("%d", (int)pal); /* UGH! */
pmg
  • 106,608
  • 13
  • 126
  • 198