258.Add Digits

tags: Easy,Math

258. Add Digits

題目描述

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

範例

Example 1:

Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2 
Since 2 has only one digit, return it.

Example 2:

Input: num = 0
Output: 0

Constraints:

  • 0 <= num <= 231 - 1

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

解答

Javascript

function addDigits(num) { if (num < 10) return num; return addDigits((num % 10) + addDigits(Math.floor(num / 10))); }

MarsgoatApr 26, 2023

function addDigits(num) { return ((num - 1) % 9) + 1; }

吉神:這題O(1)不是基本嗎?9的倍數檢查方式不是國小教的嗎??
我道歉嗚嗚嗚,我就爛。
MarsgoatApr 26, 2023

C++

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

Yen-Chi ChenWed, Apr 26, 2023

Python

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

Yen-Chi ChenWed, Apr 26, 2023

C#

public int AddDigits(int num) { if (num == 0) return 0; int r = num % 9; return r == 0 ? 9 : r; }

JimWed, Apr 26, 2023

xn10n+xn110n1+...+x110+x0=xn(9+1)n+xn1(9+1)n1+...+x1(9+1)+x0=9(...)+(xn+xn1+...+x1+x0)
忘了怎麼排版

Java

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

Ron ChenMon, Jun 12, 2023

Reference

排版教學

回到題目列表