Reverse of a number with leading zeroes

2020-03-26 05:37发布

How do we reverse a number with leading zeroes in number ? For ex: If input is 004, output should be 400.

I wrote below program but it works only when no leading zeroes in input.

int num;
cout<<"Enter number "<<endl;
cin>>num;

int rev = 0;
int reminder;
while(num != 0)
{
    reminder = num % 10;
    rev = rev * 10 + reminder;
    num = num / 10;
}
cout<<"Reverse = "<<rev<<endl;

Is there any way to input a number with leading zeroes ? Even then, Above logic doesn't work for such numbers.

Any simple solution ? It is doable by taking input as string and processing it. But that doesn't look nice.

*EDIT: If length of number is known, it looks to be possible to reverse a number with leading zeroes. (Without using string)*

I shall post the code as soon as it works.

EDIT 2: I tried to put back characters to cin stream and then read and calculate the reverse. It is working for 2 digit numbers.

But if length is known, its far easier to find reverse. All i need to do is, multiply by 10 for required number of times. So i think, i would go with string approach. Hoping that interviewer would be happy :)

标签: c++
10条回答
趁早两清
2楼-- · 2020-03-26 06:00

Once you convert your input to an integer, which you do in line 3, any information about the leading zeroes in the input of the user is lost.

You'll have to use a string.

查看更多
何必那么认真
3楼-- · 2020-03-26 06:03

Keep the number as a string, and use std::reverse.

std::string num;
std::cout << "Enter number " << std::endl;
std::cin >> num;

std::string rev(num);
std::reverse(rev.begin(), rev.end());

std::cout << "Reverse = " << rev << std::endl;
查看更多
神经病院院长
4楼-- · 2020-03-26 06:03
s = int(raw_input(" enter the no of tyms :"))
n = 0
list, list1 = [], []

while n <= s:
    m = raw_input("enter the number:")
        n=n+1
        list.append(m)

print list
list.reverse()
print list

Reverse in one of the best lang Python.

查看更多
乱世女痞
5楼-- · 2020-03-26 06:05

As ChrisF said, you need to load a string, because 4 and 004 is the same int and you cannot distinguish it after you assign it to an int variable.

The next thing to do is trim the string to contain just digits (if you want to be correct) and run std::reverse on it - and you're done.

查看更多
登录 后发表回答