LeetCode 258. Add Digits

简介: 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

v2-e30fd81f7c1406f9b32f668631ae2cfd_1440w.jpg

Description



Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.


Example:


Input: 38

Output: 2

Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.

Since 2 has only one digit, return it.


Follow up:

Could you do it without any loop/recursion in O(1) runtime?


描述



给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。


示例:

输入: 38

输出: 2

解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。


进阶:

你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?


思路



  • 数字19分别对应19,数字1018分别对应19,数字1917分别对应19,即从1开始,9个数字作为一个循环.
  • 我们用当前的数罪9取模,如果求模结果为0返回9,如果不为零返回求模运算的结果,如果num本身就是0我们直接返回0.


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-02-02 23:27:58
# @Last Modified by:   何睿
# @Last Modified time: 2019-02-02 23:29:33
class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num == 0: return 0
        b = num % 9
        return b if b != 0 else 9


源代码文件在这里.


目录
相关文章
|
8月前
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
29 0
|
10月前
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #2 Add Two Numbers
|
算法
LeetCode 423. Reconstruct Original Digits
给定一个非空字符串,其中包含字母顺序打乱的英文单词表示的数字0-9。按升序输出原始的数字。
85 0
LeetCode 423. Reconstruct Original Digits
LeetCode 415. Add Strings
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
69 0
LeetCode 415. Add Strings
LeetCode 402. Remove K Digits
给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。
57 0
LeetCode 402. Remove K Digits
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
59 0
LeetCode 241. Different Ways to Add Parentheses
LeetCode 67. Add Binary
给定两个二进制字符串,返回它们的总和(也是二进制字符串)。 输入字符串都是非空的,只包含字符1或0。
60 0
LeetCode 67. Add Binary
|
存储
Leetcode-Medium 2. Add Two Numbers
Leetcode-Medium 2. Add Two Numbers
57 0
|
Python
Leetcode-Easy 989. Add to Array-Form of Integer
Leetcode-Easy 989. Add to Array-Form of Integer
118 0