c++ - 反转数字而不将其转换为 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;
}
解决方案
如果不允许对数字使用 a std::string
,std::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
推荐阅读
- string - 将列表与另一个没有循环的列表python合并
- python - Python Elasticsearch 不接受数据体
- cloud-foundry - 无法从 Visual VM 远程连接
- phoenix-framework - 如何在长生不老药中使用特斯拉发出帖子请求
- python - json.loads 在 python 中不起作用(来自 Automate the Boring Stuff ch. 14)
- xaml - 如何在 ListView XAML 中添加多个 Frame
- python - 试图确定我的数据集中三列的四分位数
- shell - 用于监视持续更新文件的 Shell 脚本
- r - 为R中的组中的每一行分配排名
- slack - 使用内部网络上的松弛按钮测试登录