Algorithm:88.Merge Sorted Array
问题
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit1.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
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?
- Level: Easy
看完题目,之后列举了几个。分别是小于9的,是9的倍数,不是9的倍数。进行归纳如下:
- n < 9 直接返回n;
- n mod 9 = 0 直接返回9, 比如n=18
- n mod 9 != 0 直接返回 n mod 9
后面看到讨论中,说是 digit root problem2。
根据上述的分析,可以直接写出解法,具体如下:
1 | public int addDigits(int num) { |
分析
- 时间复杂度为O(1);
相关资料
Author: cloudfeng
Link: https://cloudfeng.github.io/2018/07/29/arts/algorithm/A-258-add-digits/
License: 知识共享署名-非商业性使用 4.0 国际许可协议