How do I split an int into its digits?

前端 未结 15 1540
渐次进展
渐次进展 2020-11-27 17:51

How can I split an int in c++ to its single numbers? For example, I\'d like to split 23 to 2 and 3.

15条回答
  •  暖寄归人
    2020-11-27 18:01

    Based on icecrime's answer I wrote this function

    std::vector intToDigits(int num_)
    {
        std::vector ret;
        string iStr = to_string(num_);
    
        for (int i = iStr.size() - 1; i >= 0; --i)
        {
            int units = pow(10, i);
            int digit = num_ / units % 10;
            ret.push_back(digit);
        }   
    
        return ret;
    }
    

提交回复
热议问题