码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Add Digits

时间:2015-08-16 14:58:27      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[LeetCode] Add Digits

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4734238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!