Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

各位相加 #23

Open
Aras-ax opened this issue Mar 26, 2019 · 0 comments
Open

各位相加 #23

Aras-ax opened this issue Mar 26, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Mar 26, 2019

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

示例:

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

进阶:

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

解答

function addDigits(num) {
    return num == 0 ? 0 : (num % 9 == 0 ? 9 : (num % 9));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant