How do I split an int into its digits?

前端 未结 15 1504
渐次进展
渐次进展 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:00

    The following will do the trick

    void splitNumber(std::list& digits, int number) {
      if (0 == number) { 
        digits.push_back(0);
      } else {
        while (number != 0) {
          int last = number % 10;
          digits.push_front(last);
          number = (number - last) / 10;
        }
      }
    }
    

提交回复
热议问题