How to keep leading zeros?

Hello,

I am trying to make a program to reverse an integer and store it in a variable (without using arrays). For example if user enters 12345 as input, then output should be 54321. I have made it but the only problem are leading zeros. They get eliminated automatically. Like, if I enter input as 007, it will give output 7 but it should be 700. Below is the code I have made. I am looking for a simple solution to this problem without using advance techniques because I am a beginner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "stdafx.h"
#include <iostream>
using namespace std;

void main() {

	int num, original, reversed = 0;

	cout << "\n Enter an integer value to reverse it: ";
	cin >> num;

	original = num;

	while (num) {

		reversed = reversed * 10;
		reversed = reversed + (num%10);
		cout << reversed << endl;
		num = num / 10;
	}

	cout << "\n\n\tReversed Number = " << reversed << ". ";

	if(original == reversed) {
		cout << "It is a palindrome.\n\n";
	}
	else {
		cout << "It is not a palindrome.\n\n";
	}

	system("pause");

}
Last edited on
Count the number of zeros you come across:

number_of_zeros=0;
if(num%10==0)
number_of_zeros++;

Then:

while(number_of_zeros!=0)
{
printf("0");
number_of_zeros--;
}

then print the number you obtained in the while you've written above and thats it.
Last edited on
Thank you very much for your reply. But it didn't solve my problem.

When you store "007" in a variable, let's say , of "int" type, it stores "7" but not "007. So before performing any operation, zeros are already eliminated.

Method you suggest above works for trailing zeros though. Like, if our input is "700" it will work.
Well you could also store your number in a string. that way, you won't lose any zeros.
I would have done that if I didn't need to check after reversing that whether the given number is a palindrome or not.
It's easier to check for palindromes if you save your numbers as strings. Since you're not doing any calculations, that really is the best option.

1
2
3
4
5
6
7
#include <string>
#include <iostream>
using std::string;
string s = "00000091";
for (int i = s.length()-1; i >= 0; --i) {
  std::cout << s[i];  
}
@ITFreak

Make a copy of the string of numbers first, send the copy to be reversed, then compare the the two strings. If they're the same, it's a radar number, same forward and backward.
Thank you mirceam91, Gaminic and whitenite1. I got my answer. :)
Topic archived. No new replies allowed.