Visitar URL original
learning_python/solution/0200-0299/0258.Add Digits/README.md at main · bomeng/learning_python · GitHub
Skip to content

Latest commit

 

History

History
118 lines (84 loc) · 1.99 KB

README.md

File metadata and controls

118 lines (84 loc) · 1.99 KB
comments true
difficulty 简单
edit_url https://github.com/doocs/leetcode/edit/main/solution/0200-0299/0258.Add%20Digits/README.md
tags
数学
数论
模拟

English Version

题目描述

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

 

示例 1:

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

示例 2:

输入: num = 0
输出: 0

 

提示:

  • 0 <= num <= 231 - 1

 

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

解法

方法一

Python3

class Solution:
    def addDigits(self, num: int) -> int:
        return 0 if num == 0 else (num - 1) % 9 + 1

Java

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

C++

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

Go

func addDigits(num int) int {
	if num == 0 {
		return 0
	}
	return (num-1)%9 + 1
}

Rust

impl Solution {
    pub fn add_digits(mut num: i32) -> i32 {
        ((num - 1) % 9) + 1
    }
}