I wanted to display the digits in a row. The problem I encountered was a number that ends in zero will drop the zero when reversed. So I used this code to be able to display a number with a leading zero. I'm sure there's a more elegant way using format specifiers, but I was happy to get this to work.
//
// main.m
// Program 5.8 - reverse digits of number
//
// Created by Dennis Henley on 9/22/11.
// Copyright 2011. All rights reserved.
//
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
unsigned int origNum, reverseNum, tempNum, tempNum2;
Boolean zeroFlag; //if reverse number starts with zero set flag so the zero can be displayed
//get input from keyboard
NSLog (@"Enter a positive integer to be reversed.");
scanf ("%u",&origNum);
//initialize variables
tempNum = origNum; //save origNum for later display
reverseNum = 0;
zeroFlag = FALSE;
while ( tempNum != 0) {
reverseNum *= 10; //multiply reverseNum by 10 to move 1 digit to left
tempNum2 = tempNum % 10; //grab right digit by getting remainder
if(tempNum2 ==0) zeroFlag = TRUE; //if right digit is zero set flag to allow zero display
reverseNum += tempNum2; //add right digit to reverseNum
tempNum /= 10; //remove right digit from source by dividing by 10
}
//output results
if (zeroFlag) //if zeroFlag is true, first reversed digit is zero
{
NSLog(@"The reverse of %u is 0%u", origNum, reverseNum);
}
else //no starting zero; just display number
{
NSLog(@"The reverse of %u is %u", origNum, reverseNum);
}
[pool drain];
return 0;
}
Here's sample output:
2011-09-23 08:44:37.585 reverse[1231:903] Enter a positive integer to be reversed.
45602011-09-23 08:44:56.281 reverse[1231:903] The reverse of 4560 is 0654