leetcode Add Digits
来源:互联网 发布:电脑语音朗读软件 编辑:程序博客网 时间:2024/04/29 14:27
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.
方法一:采用循环:
int addDigits(int num) { int sum;while(num/10>0){sum=0;while(num>0){sum+=num%10;num/=10;}num=sum;}return num;}
方法二:先来观察1到20的所有的最终返回值:
1------1
2------2
3------3
.
.
.8-----8
9------9
10----1
11-----2
.
.
.
18----9
19----1
20----2
由此可以发现这是以9为循环,1-9,然后是10-18,然后是19-27,以此类推,某个数字n对应返回值(n-1)%9+1:
int addDigits(int num) { int sum;sum=(num-1)%9+1;return sum;}
0 0
- [leetcode][math] Add Digits
- [leetcode] Add Digits
- 【leetcode】Add Digits【java】
- Leetcode: Add Digits
- LeetCode Add Digits
- [LeetCode] Add Digits
- leetcode 258: Add Digits
- LeetCode题解:Add Digits
- leetcode: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- [LeetCode 258] Add Digits
- LeetCode: Add Digits
- LeetCode:Add Digits
- leetcode--add digits
- leetcode Add Digits
- leetcode--Add Digits
- leetcode Add Digits
- 堆栈—冲刺十三模拟赛 外星密码
- List,Set,Map用法以及区别
- Hibernate在oracle中ID增长的两种方式
- 表单选择时变色jquery实现
- 老是忘记这些缩写,我一定是太不上心了
- leetcode Add Digits
- 深度优先搜索DFS
- having和where的性能比较
- Linux系统vmwaretools安装之后无法进入图形界面的问题
- [已解决]下载chromium源码 download_from_google_storage 无法下载文件
- Linux 使用信号量在两个进程中分别打印AAA和BBB
- Windows7旗舰版 “宽带连接错误711”的根本原因及彻底解决方法
- String的equals和==
- 从Java视角理解系统结构(一)CPU上下文切换