首页 > 解决方案 > 显示字符时如何扩展顺序?

问题描述

我需要更改符号显示的顺序,但没有递归和第二个循环

显示sow代码,但我需要获取wos

int test = 119111115; // wos

for (; test > 0; test /= 1000) {
        std::cout << (char)(test % 1000);
}
    
// > sow

不要使用字符串或与之相关的任何内容。

标签: c++

解决方案


#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;
}

推荐阅读