zoukankan      html  css  js  c++  java
  • [LeetCode] Add Digits

    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
  • 相关阅读:
    Python之函数进阶
    Python之函数初识
    Python之 文件操作
    数据类型补充
    Python 基础三
    寒假学习第五天
    寒假学习第四天
    寒假学习第三天
    寒假学习第二天
    寒假学习第一天
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4734238.html
Copyright © 2011-2022 走看看