TJU Problem 1551 Solution

Yea… I got bored tonight, can’t sleep… solved another problem.

 

Digital Roots is a little bit tricky… if you know Machine Language (Assembly) its really simple since you’re thinking registers and ascii… if you don’t know Assembly, I dropped a hint for you… try to figure it out before looking at the solution ;)

 

C++ Solution: Simple solution using a few basic C concepts… utilizing the C-style string format, input is a long string that gets checked at each character. the sum is measured through ascii values of the characters… and so forth, I’m sure you got it by now.

#include <iostream>
#include <string>

using namespace std;

int main(){
    string s;
    cin >> s;
    while (s != "0"){
        int sum = 0;
        for(int i = 0; i < s.length() ; i++)
            sum += (s[i] - 48);
        if(sum / 10 == 0)
            cout << sum << "n";
        else{
            int root = sum;
            while(root / 10 !=0){
                sum = 0;
                while (root != 0){
                    sum += root % 10;
                    root /= 10;
                }
                root = sum;
            }
            cout << sum << "n";
        }
        cin >> s;
    }

    return 0;
}
									

**For some odd reason the code box is eliminating small things like back slashes (\). So the little typos aren’t really my fault… this question has been submitted and accepted by the TJU website. **

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *