具有前导零的数字的反向 [英] Reverse of a number with leading zeroes

查看:157
本文介绍了具有前导零的数字的反向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何逆转数字中前导零的数字?
例如:如果输入是004,
输出应该是400.

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.

* 编辑:如果数字的长度已知,非零。(不使用字符串)

* 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.

编辑2:我试图把字符放回到cin流,然后读取并计算相反。它适用于2位数字。

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.

但如果长度已知,它更容易找到相反。我需要做的是,乘以10所需的次数。
所以我想,我会去与字符串的方法。
希望面试官快乐:)

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> int , double 等)所以你可能需要使用 std :: string 。读取字符串中的输入,然后调用 std :: reverse()将该字符串作为输入。

Leading zeroes are not represented by binary numbers (int, double, etc.) So you'll probably have to use std::string. Read the input into the string, then call std::reverse() passing the string as input.

这篇关于具有前导零的数字的反向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆