反转数字时用零填充

时间:2017-02-15 19:35:43

标签: c++

我正在开发一个程序,它有一个功能,目的是反转三位数字。代码看起来像

int reverseFunction(int userNumber){ 
    int reverse = 0,mod; 
    while (userNumber != 0)
    {
        mod = userNumber%10;
        reverse = reverse*10 + mod; 
        userNumber /= 10; 
    }

    return reverse;
}

这很有效,除非你传递一个数字,第一个数字只比最后一个数字大1。后面会调用反向,如果上述情况属实,则最终会得到一个两位数的数字。例如

The number you entered is: 473.

The reversal of the input is: 374.

Subtraction of reversal from the original number is: 99.

Reversal of the resulting number is: 99.

Addition of the number to the un-reversed form is: 198.

The final outcome should be: 1089, which is our “Magic Number”.

如果'99'填充零'099',它会吐出1089,这是正确的数字。如何解决这个问题并填零?我已经看到了输出零的方法,但没有用零计算。我正在使用c ++。

2 个答案:

答案 0 :(得分:0)

您的plot()功能没有任何问题。看起来您遇到的问题是代码的另一部分。即:在代码中为其原始的非反转形式添加反转数字。

要使其按照您需要的方式行事,首先要检查数字是否有1,2或3位,并相应地执行添加。

例如:

reverse()

答案 1 :(得分:0)

那是因为你的反向函数对于各种数字的数字都是通用的。因此,您应该明确指定您想要的位数:

#include <math.h> 
int reverseFunction(int userNumber,int numOfDigits)
{ 
    int reverse = 0,mod; 
    int digitsCount = 0;
    while (userNumber != 0)
    {
        mod = userNumber%10;
        reverse = reverse*10 + mod; 
        userNumber /= 10; 
        digitsCount++;
    }
    return reverse*pow(10,numOfDigits-digitsCount);
}

现在应该为所有类型的数字做填充。