反向输出前导零

时间:2016-09-11 20:07:32

标签: c++ algorithm formatting

下面的代码适用于将数字反转为零

Enter a positive integer: 650
The number 650 reversed is: 056

但不适用于此

Enter a positive integer: 045
The number 45 reversed is: 54

我一直在寻找540而不是54

我遇到了上一个问题:

Is it possible to store a leading zero in an int?

格式化仍然是修复我的代码的答案 - 如果是,那么添加它的位置。或者这是一个不同的问题。再次感谢您的洞察力

#include <iostream>
#include <iomanip>

using namespace std;

int main() {

 int number, disp_num, c_num, check_num =0, count = 0, rev_count=0, reverse = 0;


cout << "Enter a positive integer: ";
cin>> number; 

while(number < 0){
    cout << "That number is not positive. Enter a positive integer: ";
    cin >> number;
}

disp_num = number;



  for( ; number!= 0 ; )
  {
  reverse = reverse * 10;
  reverse = reverse + number%10;
  number = number/10;
  count += 1;
  }

 c_num = reverse;

 for( ; c_num!= 0 ; )
{
   check_num = check_num * 10;
   check_num = check_num + c_num%10;
   c_num = c_num/10;
   rev_count += 1;
 }

if (rev_count != count){
    cout << "The number " << disp_num << " reversed is: ";
    for (int i = 0; i < (count - rev_count); i++){
        cout << "0";
    }
    cout << reverse << endl;
}

else{
cout<< "The number " << disp_num << " reversed is: " <<reverse << endl;
}
return 0;

2 个答案:

答案 0 :(得分:0)

正如Pete Becker所说,使用字符串,而不是实际值。无法反转数字并将前导零保持在简单的int或任何原语中。你需要某种类型的结构来跟踪有多少前导零。

#include <string>
#include <sstream>
#include <iostream>

std::string reverse(unsigned num) {
    std::stringstream ss;
    for(; num > 0; num /= 10)
        ss << num % 10;
    return ss.str();
}

int main(){
    std::cout << reverse(12340) << std::endl;  // prints "04321"
    std::cin.get();
    return 0;
}

答案 1 :(得分:0)

由于编译器忽略它,因此无法获得最左边的零值。解决方案是将输入作为字符串而不是整数值。 如果您希望输入为int,则调用一些转换函数,如atoi()...

考虑一下:

#include <iostream>
#include <string>
using namespace std;


int main()
{

    typedef string str;

    str strValue, strTmp;;
    char c;

    cout << "Enter value: ";

    while('\n' != cin.peek() && isdigit(cin.peek()))
    {
        c = cin.get();
        strValue += c;
    }

    cout << "strValue: " << strValue << endl;

    for(int i(strValue.length() - 1); i >= 0; i--)
        strTmp += strValue[i];

    strValue = strTmp;

    cout << "strValue: " << strValue << endl;


    return 0;
}