LeetCode 258. Add Digits
来源:互联网 发布:清除localstorage数据 编辑:程序博客网 时间:2024/06/07 01:16
Description
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?
Analysis
这个问题叫做Digital root。实际上,随手写几个便会发现,答案序列是这样的:
0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9…
只需要得到上述
这两个公式对应了Version 1与Version 2。
Code
Version 1
class Solution {public: int addDigits(int num) { if (num == 0) return 0; return (num % 9 == 0)? 9 : num % 9; }};
Version 2
class Solution {public: int addDigits(int num) { return 1 + (num - 1) % 9; }};
Appendix
- Link: https://leetcode.com/problems/add-digits/
- Run Time:
- Version 1: 6ms
- Version 2: 3ms
0 0
- 【LeetCode】258.Add Digits
- LeetCode 258. Add Digits
- LeetCode : 258. Add Digits
- leetCode 258. Add Digits
- LeetCode 258. Add Digits
- 258. Add Digits LeetCode
- LeetCode 258. Add Digits
- LeetCode 258. Add Digits
- leetcode 258. Add Digits
- [LeetCode]258. Add Digits
- LeetCode 258. Add Digits
- <LeetCode>258. Add Digits
- leetcode--258. Add Digits
- LeetCode 258. Add Digits
- LeetCode *** 258. Add Digits
- Leetcode 258. Add Digits
- 258.[LeetCode]Add Digits
- 【leetcode】258. Add Digits
- 数据结构(c++)(3)--简单的计算器
- 3DES和SHA-1
- svg中path标签的用法
- 辨析离线算法与在线算法
- Mac 下 制作USB Clover引导
- LeetCode 258. Add Digits
- 如何在只听过一次的情况下用百度找到歌名
- 【笔记】使用Spring表单标签
- Android从零开搞系列:自定义View(12)贝塞尔曲线的应用
- 实用的4~20mA输入/0~5V输出的I/V转换电路
- 函数的数据传递
- 科锐课堂笔记:2017/4/21 多重继承与智能指针
- 随机梯度下降算法
- Servlet url-pattern /与/*区别,*.action以及SpringMVC中/*解析出错过程分析