How do I split an int into its digits?

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

    the classic trick is to use modulo 10: x%10 gives you the first digit(ie the units digit). For others, you'll need to divide first(as shown by many other posts already)

    Here's a little function to get all the digits into a vector(which is what you seem to want to do):

    using namespace std;
    vector digits(int x){
        vector returnValue;
        while(x>=10){
            returnValue.push_back(x%10);//take digit
            x=x/10; //or x/=10 if you like brevity
        }
        //don't forget the last digit!
        returnValue.push_back(x);
        return returnValue;
    }
    

提交回复
热议问题