LeetCode --- Add Digits解题分析
来源:互联网 发布:返回顶部js代码 编辑:程序博客网 时间:2024/06/07 22:03
题目内容:将一个非负整数,通过不断循环将各个位置上的数字相加,最终为一位数时即为所求结果。比如:
num = 383 + 8 = 111 + 1 = 2结果就输出2
int solution1(int n){//调用getSum,判断返回值如果不是一位数继续调用getSum求和int result = getSum(n);while(result > 9){result = getSum(result);}return result;}int getSum(int n){//求一个数的各位数相加之和int sum = 0;while(n > 0){sum += (n%10);n = n/10;}return sum;}
解题思路二:以三位数字为例,设num=xyz
num = x * 100 + y * 10 + z = x + y + z + ( x * 99 + y * 9 )
(1)则后面部分一定可被9整除,所以num%9的结果与(x+y+z)%9的结果一样;
(2)因为(x + y) % z = (x % z + y % z) % z,又因为 x % z % z = x % z;
(3)因为最终一位数的结果肯定为0-9,而0-8模9仍是原来的数,9%9=0,显然违背题意
综上所述结果可以写成 (num - 1) % 9 + 1,只模除9一次,并将模除后的结果加一返回即为所求
int solution2(int n){return (n-1)%9 + 1;}
0 0
- LeetCode --- Add Digits解题分析
- LeetCode-Add Digits-解题报告
- 【LeetCode解题报告】Add Digits
- 【LeetCode】 Add Digits 解题报告
- [leetcode] 258. Add Digits 解题报告
- LeetCode 258.Add Digits 解题报告
- leetcode解题报告258. Add Digits
- [Leetcode] 258. Add Digits 解题报告
- leetcode解题报告258——Add Digits
- [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
- 1034. 有理数四则运算(20)
- FragmentActivity和Activity的具体区别在哪里
- mapreduce编程(一)-二次排序
- 一些开源的项目
- Android进程与线程
- LeetCode --- Add Digits解题分析
- SublimeText3 配置前端开发插件
- 浙大PAT1059 Prime Factors
- bzoj3991: [SDOI2015]寻宝游戏
- java字符串转16进制
- C++pair的用法
- C++Primer第5版读书笔记(第4章)
- [Python入门]Chapter10 列表
- ModelDriven背后的机制和Action,valueStack,Model,Context之间的关系图