[LeetCode] 258. Add Digits

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?


class Solution {

    public int addDigits(int num) {

        // 將num除以10 然後將所有餘數相加

        // 如果sum(餘數)除以10 ==0 return 餘數

        // num除以10 然後將所有餘數相加

         //!!不能用迴圈或遞迴

        

        int remind = 0;

        int temp = 0;

        while(num != 0){ 

            remind += num % 10;

            num /= 10;

               if(num==0 && remind>=10)

                {

                    num = remind;

                    remind = 0;  //忘記歸零,搞好久

                }

        }

                return remind;

      }

}

留言

這個網誌中的熱門文章

[HTML]標籤-下

論P, NP, NP-Complete, NP-Hard問題

[Python]基礎課程

[系統]解除電腦限制頻寬

[HTML]標籤-上

[AlaSQL] 多data查詢+累計

How to Check the MySQL Version

[SQL Sever] 日期時間

推薦使用的9款編程字體

類別型態 vs 基本型態