leetcode/258. Add Digits
来源:互联网 发布:贪心算法的基本思想 编辑:程序博客网 时间:2024/05/16 03:44
//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?
solution 1
int addDigits(int num) { if(num) { int res = num % 9; return (res == 0)? 9:res; } else { return num; }}
solution 2
int addDigits(int num) { int res = num % 9; return (res != 0 || num == 0)? res:9;}
solution 3
int addDigits(int num) { return (num - 1) % 9 + 1;}
//根据同余定理10^n ≡ 1 (mod 9)得a_n10^n + … + a_110 + a_0 ≡ a_n + … + a_1 + a_0 (mod 9)
//其中a_n表示位数的系数,综上所述,取模后能够得到各个位数系数和,且这系数和是小于9的整数
//当且仅当n对9取模为零时侯要分开考虑,n%9 = 0 ,当给的num是0是,返回值才为0,否则返回9
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
- centos yum报错Loaded plugins: fastestmirror
- Spring MVC 学习笔记 三 handlerMapping和handlerAdapter
- 编写实现堆排序的算法。
- “全文”和“收起”实现
- C语言实现两台电脑通过串口通信
- leetcode/258. Add Digits
- hdoj 1025 Constructing Roads In JGShining's Kingdom ( LIS +二分法STL )
- iOS开发 pod install遇到的问题If none exists, create a ticket, with the template displayed above
- 曼哈顿距离最小生成树与莫队算法
- elasticsearch批量index,update,delete——Bulk Helpers
- warning C4018: “<”: 有符号/无符号不匹配
- mysql问题解决:mysqladmin: connect to server at 'localhost' failed
- [Java]Socket和ServerSocket学习
- Spring MVC 学习笔记 四 Viewresol和View