258. Add Digits The digits are added to only one digit

[copy title]:

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

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

 [brute force solution]:

Time analysis:

Space Analysis:

 [Optimized]:

Time analysis:

Space Analysis:

[Wonderful output conditions]:

[Wonderful corner case]:

[Thinking question]:

[One sentence idea]:

%9

[Input amount]: Empty: Normal situation: Extra large: Extra small: Special situations handled in the program: Abnormal situations (Illegal and unreasonable input):

[Paint]:

[One brush]:

if + else if is not complete, if + else is complete

[Second brush]:

[Three brushes]:

[Four brushes]:

[Five brushes]:

  [Results of five-minute naked eye debug]:

[Summarize]:

if + else if is not complete, if +  else is complete

[Complexity]: Time complexity: O(1 ) Space complexity: O(1 )

[English data structures or algorithms, why not use other data structures or algorithms]:

[Key templating code]:

[Other solutions]:

[Follow Up]:

[The topics given by LC change and change]:

 [Code style]:

class Solution {
    public int addDigits(int num) {
        if (num == 0) 
            return 0;
        
       if (num % 9 == 0) {
           return 9;
       }
        
       else{
           return num % 9;
       }
    }
}
View Code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325108983&siteId=291194637