Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

algorithm - C - reverse a number

I am coding in C on linux, and I need to reverse a number. (EG: 12345 would turn into 54321), I was going to just convert it into a string using itoa and then reverse that, as it's probably a lot easier with string manipulation, however it turns out itoa is non standard and isn't included in gcc. Is there a way of doing a binary rotation style thing on decimal numbers and if not what approach should I take?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
int n;
scanf("%d",&n);
int rev=0,rem;
while(n>0)
{
    rem=n%10; //take out the remainder .. so it becomes 5 for 12345
    rev=rev*10+rem; //multiply the current number by 10 and add this remainder.
    n=n/10; //divide the number. So it becomes 1234.
}
printf("%d",rev);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...