c++ - 显示字符时如何扩展顺序?
问题描述
我需要更改符号显示的顺序,但没有递归和第二个循环。
显示sow
代码,但我需要获取wos
int test = 119111115; // wos
for (; test > 0; test /= 1000) {
std::cout << (char)(test % 1000);
}
// > sow
不要使用字符串或与之相关的任何内容。
解决方案
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
int main() {
// your code goes here
int test = 119111115; // wos
for (; test > 0;) {
string temp = std::to_string(test);
// Get first three characters and convert it to ASCII char
std::cout << (char) stoi(temp.substr(0, 3));
if (temp.size() > 3 )
// Remove first three characters
test = stoi(temp.erase(0,3));
else
test = 0;
}
return 0;
}
输出:
wos
如果你想摆脱to_string
,你可以
#include <algorithm>
#include <string>
#include <cmath>
#include <iostream>
using namespace std;
unsigned int number_of_int( unsigned int n )
{
unsigned int number_of_digits = 0;
do {
++number_of_digits;
n /= 10;
} while (n);
return number_of_digits;
}
int main() {
// your code goes here
int test = 119111115; // wos
for (; test > 0;) {
// int length = to_string(test).length();
// int length = number_of_int(test);
int length = test == 0 ? 1 : log10(std::abs(test)) + 1;
int first3 = test / pow(10, length-3);
std::cout << (char) first3;
if (length > 3)
// Remove first three characters
test = test % (unsigned long)pow(10, length-3);
else
test = 0;
}
return 0;
}
推荐阅读
- laravel - 国家列的 Laravel 下拉菜单不起作用
- php - (字符串)在 php/mysql 准备好的语句中是什么意思?
- resources - 使用 terraform 删除特定资源,即 vm、nic、nsg
- python - Pylint 加载插件在 VS Code 中失败
- sql - 将显示 2 个数据总和的列连接在一起
- java - 一个接一个地创建新元素
- javascript - 通过管道而不是 websocket 连接 Puppeteer 的优缺点是什么
- angular - 角度路由返回空页面
- image - RMSE Landsat8 AVHRR
- android - Cloud firestore Flutter 无法在文档上设置数据