'Program to reverse a number without using an array
This is the code that I used. It works perfectly, but I don't understand why it works. I just kept changing my original logic until I started using -1 in the counter loop.
#include<stdio.h>
#include<math.h>
int main(){
int number, reverse, sum =0;
scanf("%d", &number);
int temp = number;
int ctr;
for(ctr = -1; temp!=0; ctr++)
temp = temp/10;
while(number)
{
sum = sum + (number%10 * (pow(10, ctr--)));
number = number/10;
}
printf("%d", sum);
return 0;
}
Solution 1:[1]
same basic math but so much easier to understand:
unsigned int number = 123456789;
unsigned int reversed = 0;
do {
reversed *= 10;
reversed += number % 10;
number /= 10;
} while (number > 0);
Solution 2:[2]
Although this is kind of awkward to explain the logic of the code that you wrote it yourself, I understood the logic behind it.
Indeed, I was looking for a solution to solve this problem: How to reverse any positive integer without using arrays or indexed variables to which your code was the solution I was looking for.
The logic of your programme is like this:
you first count the digits of the given number in the FOR-loop in the shortest possible way. you need this because you have to 10-power each remainder up to digits of the given number in the next WHILE-loop and you store/add the result of this each time in the variable named SUM. The final result of this would be the whole integer to be reversed.
PS1:
You do not need the variable named REVERSE. Just drop it or replace SUM with it.
PS2: You really do not need to go that long way to do this. Here's another shorter version:
#include <stdio.h>
void main (void){
unsigned short int uNum, nReversed;
puts ("Enter a positive integer number: ");
scanf ("%hu", &uNum);
while (uNum != 0){
nReversed = uNum%10 + nReversed*10 ;
uNum /= 10;
}
printf ("\n\n\nThat is %d", nReversed);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | atb |
Solution 2 |