首页 > 解决方案 > 反转数字而不将其转换为 C++ 中的字符串

问题描述

我正在尝试用c ++编写一个程序来反转一个数字,它可以使用像1234这样的数字,但是如果我尝试输入像5430这样的数字,它会显示345,并且如果数字以零开头,则相同,例如:如果输入0234它将显示 432。

有人可以告诉我如何在开始和结束时处理零。

我必须只存储数字而不将其转换为字符串

#include<iostream>

using namespace std;

int main(){
    int n;
    int lastdigit;
    cin >> n;
    int reverse = 0;
    while(n!=0){
        

        lastdigit = n % 10;
        reverse = reverse * 10 + lastdigit;
        n = n / 10;
    }
    cout << reverse<<endl;
}

标签: c++

解决方案


如果不允许对数字使用 a std::stringstd::reverse则可以将位数存储在原始数字中,并使用 I/O 操纵器std::setw(),并std::setfill()在打印反转数字时添加前导零。

例子:

#include <iomanip>
#include <iostream>

int main(){
    int n = 5430;
    
    int reverse = 0;
    int no_of_digits = 0;
    bool neg = n < 0;
    if(neg) n = -n;

    while(n!=0) {
        ++no_of_digits;
        reverse = reverse * 10 + (n % 10);
        n = n / 10;
    }
    
    std::cout << std::setw(no_of_digits) << std::setfill('0') << reverse;
    
    if(neg) {
        reverse = -reverse;
        std::cout << '-';
    }
    std::cout << '\n';
}

输出:

0345

推荐阅读