程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> LeetCode 258 Add Digits(數字相加,數字根)

LeetCode 258 Add Digits(數字相加,數字根)

編輯:關於C++

翻譯

給定一個非負整型數字,重復相加其所有的數字直到最後的結果只有一位數。

例如:

給定sum = 38,這個過程就像是:3 + 8 = 11,1 + 1 = 2,因為2只有一位數,所以返回它。

緊接著:

你可以不用循環或遞歸在O(1)時間內完成它嗎?

原文

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 = 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?

分析

其實我並不會寫,循環和遞歸都不能用……我還能怎麼辦吶。

然後看了LeetCode上給的提示,看了維基百科的一篇文章:Digital root。

這裡寫圖片描述

有了這個的話,就很容易了;具體這個公式的細節,大家自己參看維基吧,因為篇幅過長就不翻譯了。

代碼

class Solution {
public:
    int floor(int x) {
        return (x - 1) / 9;
    }
    int addDigits(int num) {
        return num - 9 * floor(num);
    }
};
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved