256ms Java one-line solution


  • 8
    S
    public class Solution {
        public int addDigits(int num) {
            return (num - 1) % 9 + 1;
        }
    }

  • 0

    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.


  • 0

    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.


  • 0
    S

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


  • 2

    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:
        int addDigits(int num) {
            return num - (num - 1) / 9 * 9; 
        } 
    };
    

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


  • 0
    S

    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)


  • 0

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

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

  • 0
    P

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


  • 0

    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.


  • 0
    P

    Thank you very much!


  • 0
    S

    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.


  • 0

    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
    

  • 0

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


  • 0
    L
    This post is deleted!

Log in to reply
 

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