258Add Digits
来源:互联网 发布:淘宝闺蜜投诉平台 编辑:程序博客网 时间:2024/05/29 17:36
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.
https://en.wikipedia.org/wiki/Digital_root
Solution1 Straightforward way
public class Solution { public int addDigits(int num) { while(num>=10){ num = (num/10)+num%10; } return num; }}简单的问题总是会有简单的方法,如果你没有找到,也只是说明你没有找到而已。一个数的数字根(digit root)就是将该数的所有数字加起来,循环往复,直到只有一位数字为止。譬如 345, 3+4+5=12,1+2=3,那么 345 的数字根就是 3。代码可以如此简单,只要你发现了 root(10x+y) = root(x+y) 实际上 root(x) = x % 9 这个真相就好了。 也就是一个数 n 的数字根就是 n % 9 !不过因为数 n 除了 0 时数字根是 0 之外,其他时候是取值 1 - 9,所以 n % 9 如果为 0 的时候数字根是 9 !用一个小技巧处理便是: (n-1) % 9 + 1 !
int addDigits(int num) { return (num-1)%9+1;}
0 0
- [258] Add Digits
- 258 Add Digits
- leetcode 258: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- 258-e-Add Digits
- 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 - Add Digits
- LeetCode 258 : Add Digits
- 【LeetCode】258 Add Digits
- Leetcode - 258 - Add Digits
- leetcode 258 :Add Digits
- [树状数组+上升子序列] HDU 3030 Increasing Speed Limits
- 在listView适配器的内存优化给点击事件带来的麻烦
- 普通内部类详解
- c++ builder TADOQuery控件的type mismatch for field‘note',expecting: String actual: Memo.
- RMQ算法
- 258Add Digits
- ROS 进阶学习笔记(12) - Communication with ROS through USART Serial Port
- Android日志系统驱动程序Logger源代码分析
- RMQ (Range Minimum/Maximum Query)算法
- iOS视图控制对象生命周期-init、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear、viewDidDisappear的区别及用途
- myeclipse中java文件头注释格式设置
- C和C++库中的排序函数——sort与qsort解析
- ORA-02019:未找到远程数据库的连接说明(数据库链接创建)
- Windows编程之COM组件