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();
}
In
you are computing the number of digits that
numberhas, that’s one more than the exponent of the highest power of ten not exceedingnumber. You need to decrementjafter that.But using
pow()is not the best way, far better is to construct the reversed number incrementally: