# My accepted c++ solution with O(1) time without using the hint about the theory

• ``````int addDigits(int num)
{
if (num <= 9) return num;

int maxNumDigits = 10;
string numStr = std::to_string(num);
numStr = "00000000" + numStr;
numStr = numStr.substr(numStr.size() - maxNumDigits);

int result = (numStr.at(0) - '0') +
(numStr.at(1) - '0') +
(numStr.at(2) - '0') +
(numStr.at(3) - '0') +
(numStr.at(4) - '0') +
(numStr.at(5) - '0') +
(numStr.at(6) - '0') +
(numStr.at(7) - '0') +
(numStr.at(8) - '0') +
(numStr.at(9) - '0');
if (result <= 9) return result;

numStr = std::to_string(result);
numStr = "00000000" + numStr;
numStr = numStr.substr(numStr.size() - maxNumDigits);

result = (numStr.at(8) - '0') +
(numStr.at(9) - '0');
if (result <= 9) return result;

numStr = std::to_string(result);
numStr = "00000000" + numStr;
numStr = numStr.substr(numStr.size() - maxNumDigits);

result = (numStr.at(8) - '0') +
(numStr.at(9) - '0');
if (result <= 9) return result;

// should be done by now
return -1;
}``````

• Or simply,

``````int addDigits(int num) {
if (num == 0)
return 0;
return (num%9 == 0)? 9: num % 9;
}``````

• Like I said, I am doing it without using that theory.

• If you're gonna be like that, why not go all the way?

``````int addDigits(int num) {
return (num - 1) % 9 + 1;
}
``````

Or even:

``````int addDigits(int num) {
return ~-num % 9 + 1;
}``````

• I am not sure what you mean by "all the way" but when I said "without using that theory" I meant without using the knowledge that "mod" will make this problem easy.

• I guess the trick to understanding my reply is that I wasn't talking to you :-)

• Oh sorry. I thought you are the same guy as above. I didn't really look at the author name. :)

• numStr = numStr.substr(numStr.size() - maxNumDigits);

what does this state mean？

• It means to get the substring where it contains the last maxNumDigits number of characters of numStr. For example, if numStr is "00000000123" where the number of characters is 11 and maxNumDigits is 10 because that is how many characters INT_MAX has, numStr = numStr.substr(numStr.size() - maxNumDigits) is numStr = numStr.substr(1) which leads to numStr being "0000000123".

• thanks a lot buddy

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.