# 256ms Java one-line solution

• ``````public class Solution {
return (num - 1) % 9 + 1;
}
}``````

• Great solution! BTW, how do you see the running time. I try to click the "More Details" but it does not open the performance page.

• There's a bug on the "More details" button, I'll fix it soon. Meanwhile you can click on the "Accepted" to view more details. Yes, the status text is actually a link.

• "Accepted" seems not working either. I saw my running time after I clicked on the "Submissions" on the top of the page

• Great solution! Well, it seems that Pythoners will not be able to use such a nice code since `(0 - 1) % 9 = 8` in Python and so the result for input `0` will be wrong.

I have another 1-line solution, a little longer than yours. Well, I think your code is more elegant :-)

``````class Solution {
public:
return num - (num - 1) / 9 * 9;
}
};
``````

Update: Well, this code is also not applicable in Python since Python decides `-1 / 9` to be `-1`...

• Well it doesn't take much extra time in python adding "if num == 0" :-)
But in Java adding "if (num == 0)" increase the running time from 256ms to 292ms, even a bit slower than straightforward solution...(284ms)

• Yeah, the `if` for `0` can also be condensed into one line :-)

``````class Solution:
# @param {integer} num
# @return {integer}
return (num - 1) % 9 + 1 if num else 0``````

• Can someone explain this answer please, I don't understand why it works. Thank you guys.

• Hi, primenumber123. Try to work through from `num = 1` to `num = 20`, and you will see that the result is just a periodical reoccurrence of the sequences `1, 2, ..., 9`. So you just have to code that regularity.

• Thank you very much!

• I suppose the only tricky thing occurs when adding 1 to ...xyz9 to ...xy(z+1)0. Say addDigits(...xyz9) = n. If z < 9 then obviously addDigits(...xy(z+1)0) = addDigits(n + 1). If z == 9 and y < 9 then ...xyz9 becomes ...x(y+1)00 and recursively we always get the same result.

• Or one of these:

``````        return num and (num - 1) % 9 + 1
return num and (num % 9 or 9)
return num % 9 or num and 9
``````

• Wow, Stefan. You are really a master in Python :-)

• This post is deleted!

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