且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Add Digits

更新时间:2022-04-14 19:24:57

Well, if you have no idea of other methods, try to compue the result for all the numbers ranging from 1 to 20 and then you will see the regularity. After you find it, this problem just needs 1-line code.

I write the following code.

1 class Solution { 
2 public:
3     int addDigits(int num) {
4         return num - (num - 1) / 9 * 9; 
5     } 
6 };

This link writes anther more elegant one.

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

However, both of them cannot be used in Python since Python says that -1 % 9 = 8 and -1 / 9 = -1. Both the codes above will give a wrong answer for input 0. So you have to handle it separately.

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