The assignment everyone has done before..lol...reversing digits. How do i make my code more simple (as my friend stated)?
Trying to write a program that reverses the digits in an integer. Assuming that the max value of the integer is 99999. And using arrays to solve the problem.
For example if integer:
0 was entered, output is 0
10 was entered, output is 1
12 was entered, output is 21
123 was entered, output is 321
7600 was entered, output is 67
8015 was entered, output is 5108
90000 was entered, output is 9
As Disch says ........but also......
1. Start with a 5 element array with all elements initializes to 0 (zero)
2. Using a for loop with condition set to i<5; enter up to 5 integers. (Pad with zeros to get to 5.)
3. Read them out backwards using i--;but if array[4]==0 don't print it. print ""
4. Test at each iteration as in 3. above.
5. However if array [i] >0 print array[i-1] even if == 0.
If you need to make several manipulations put the whole lot in a while loop.
I'm sure you will be able to improve on this... especially if I've missed something!
You don't need an array. Using a 5 element array limits you to 5 characters. It also makes you convert to a string (or a series of characters) which is wholly unnecessary.
You can do this with 2 integers and a loop. We're talking 3 or 4 lines of code.
It's Disch with an 's'. Pronounced like "Dish". The extra C is for "cool". ;D
I missed that about the max. And also I might have gotten this post mixed up with another one regarding unnecessary conversion to strings. My mistake!
I can't really give pseudocode without giving it away completely. So I'll just give it away completely:
1 2 3 4 5 6 7 8 9 10 11
int ReverseANumber( int num )
{
int rev = 0;
while( num > 0 )
{
rev *= 10; // move reversed digits to the left
rev += (num % 10); // add the rightmost digit of original number
num /= 10; // move original number digits to the right
} // repeat until number is zero
return rev;
}
Sorry about my typo Disch
Yes I can see why you include the 'c'
The code is very cool
******************************
Enter a number using 5 digits max.
90720
rev:= 0 num:= 9072
rev:= 2 num:= 907
rev:= 27 num:= 90
rev:= 270 num:= 9
rev:= 2709 num:= 0
The reverse of this number is 2709
******************************
I suppose its very obvious to you blokes but i really had to go through it with a pencil before i could get it. Many thanks