C++ get each digit in int

前端 未结 13 1291
谎友^
谎友^ 2020-12-02 21:50

I have an integer:

int iNums = 12476;

And now I want to get each digit from iNums as integer. Something like:

foreach(iNum          


        
13条回答
  •  自闭症患者
    2020-12-02 22:03

    Here is a more generic though recursive solution that yields a vector of digits:

    void collect_digits(std::vector& digits, unsigned long num) {
        if (num > 9) {
            collect_digits(digits, num / 10);
        }
        digits.push_back(num % 10);
    }
    

    Being that there are is a relatively small number of digits, the recursion is neatly bounded.

提交回复
热议问题