leetcode 258 Add Digits
来源:互联网 发布:伊登软件股份有限公司 编辑:程序博客网 时间:2024/06/03 17:52
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?
class Solution {public: int addDigits(int num) { return (num-1)%9+1; }};
设数字为四位数,各个位分别是abcd,其他情况类似。
则
abcd=a*1000+b*100+c*10+d
=a+b+c+d+(a*999+b*99+c*9)
=a+b+c+d+(a*111+b*11+c)*9
设n=a+b+c+d
n同样可以做如上展开,反复迭代,直到前面数字之和为个位数,形如n+m*9并且此时这个个位数的取得满足题目的要求的返回值,此时后面的数字为9的倍数。要求的这个个位数只需对九求模即可(因为这个数可能是9,所以要先减一最后加一)。
0 0
- leetcode 258: Add Digits
- 258Add 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
- leetcode 258 :Add Digits
- leetcode 258--Add Digits
- leetcode 258 Add Digits
- Leetcode #258 Add Digits
- LeetCode 258:Add Digits
- LeetCode 258:Add Digits
- Corel-1000 dataset Wang 数据集
- OpenGL Buffer 操作合集
- 从零开始学习C语言
- 12. php的错误和异常处理(二)
- Maven pom.xml “Plugin execution not covered by lifecycle configuration”
- leetcode 258 Add Digits
- 广义表的读取和输出,树的拷贝及比较的实现
- Spark中组件Mllib的学习15之创建分布式矩阵
- currentTimeMillis方法
- python中的*与**
- C语言项目开发-项目架构和编程命名规范
- CVonline: Image Databases 计算机视觉图像数据集
- 第十二周阅读程序2
- [SDIBT-OJ]27页