Split an Integer into its digits c++

后端 未结 12 1889
说谎
说谎 2020-11-28 15:27

I\'m trying to learn c++ on my own and I\'ve hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and

12条回答
  •  生来不讨喜
    2020-11-28 16:24

    A simple solution:

    int n = 12345;
    vector digits;
    while (n != 0) {
        digits.insert(digits.begin(), n%10);
        n /= 10;
    }
    for(auto & i : digits)
        cout << i << " ";
    

    output: 1 2 3 4 5

提交回复
热议问题