How to get the digits of a number without converting it to a string/ char array?

前端 未结 15 1251
既然无缘
既然无缘 2020-11-27 04:07

How do I get what the digits of a number are in C++ without converting it to strings or character arrays?

15条回答
  •  春和景丽
    2020-11-27 04:36

    I have seen many answers, but they all forgot to use do {...} while() loop, which is actually the canonical way to solve this problem and handle 0 properly.

    My solution is based on this one by Naveen.

    int n = 0;
    std::cin>>n;
    
    std::deque digits;
    n = abs(n);
    do {
        digits.push_front( n % 10);
        n /= 10;
    } while (n>0);
    

提交回复
热议问题