Home sumDigits.cpp
Post
Cancel

sumDigits.cpp

sumDigits.cpp

Go Back

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Link to challenge: https://edabit.com/challenge/zGW3mYCrEFqA8LF3e

#include <iostream>
#include <cstring>

using namespace std;

class SumDigits{
    private:

        string val = "";
        int total = 0;

    public:

        SumDigits(){

        }

        SumDigits(int positiveInteger){
            val = to_string(positiveInteger);
        }

        void sumDigit(){
            total = 0;
            for (int i = 0; i < val.size(); i++){
                total += stoi(val.substr(i, 1));
            }
        }

        void print(){
            cout << total << endl;
        }
};

int main(){
    SumDigits sdigits(111);
    sdigits.sumDigit();
    sdigits.print();
    SumDigits sdigits2(222);
    sdigits2.sumDigit();
    sdigits2.print();
    SumDigits sdigits3(333);
    sdigits3.sumDigit();
    sdigits3.print();
}

Console Output

1
2
3
3
6
9

Go Back

This post is licensed under CC BY 4.0 by the author.