How do I split an int into its digits?

前端 未结 15 1578
渐次进展
渐次进展 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 17:55

    Reversed order digit extractor (eg. for 23 will be 3 and 2):

    while (number > 0)
    {
        int digit = number%10;
        number /= 10;
        //print digit
    }
    

    Normal order digit extractor (eg. for 23 will be 2 and 3):

    std::stack sd;
    
    while (number > 0)
    {
        int digit = number%10;
        number /= 10;
        sd.push(digit);
    }
    
    while (!sd.empty())
    {
        int digit = sd.top();
        sd.pop();
        //print digit
    }
    

提交回复
热议问题