Add Digits | LeetCode 加数字
来源:互联网 发布:c 高级编程 第9版 编辑:程序博客网 时间:2024/05/29 04:36
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 给定一个非负整数,把每一位数字相加,直到结果只有1位为止。
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
题目的隐藏条件里提示What are all the possible results?How do they occur, periodically or randomly?
通过提示发现这些数字是按规律出现的,1-9的结果是它自身,10-18的结果是1-9,之后是19-27,28-36,37-45……(这样的数称为同余数)
先尝试对9取余,return num%9; 发现错误,9倍数都返回了0。
改为对9取余等于0时返回9,其他情况返回num%9,又出现错误,0返回了9。
再修改为等于0时返回0,通过。
int addDigits(int num) { if(num == 0) return 0; if(num % 9 == 0) return 9; return num % 9;}可以简写为
int addDigits(int num) { return num == 0 ? 0 :(num % 9 == 0 ? 9 : num % 9);}
可以利用此公式。
int addDigits(int num) { return 1 + (num - 1) % 9;}
/*********************************************************************************/
在提交记录里发现了自己第一次写的代码
int addDigits(int num) { int sum; while(num > 9){ sum = 0; do{ sum += num % 10; num /= 10; }while(num > 0); num = sum; } return num;}
0 0
- Add Digits | LeetCode 加数字
- Leetcode:258.Add Digits 加数字,直到为个位数
- 【LeetCode】 Add Digits 数字相加
- [LeetCode] Add Digits - 数字各个位数求和
- leetcode 258.Add Digits | leetcode 258 -数字相加
- Add Digits -- 增加数字
- LeetCode OJ 之 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
- System.Data.Sqlite for winform
- android 点击切换头像图片
- iOS 自定义等高cell
- 递归将十进制转化为二进制
- IOS 设计模式 桥接模式(bridge)
- Add Digits | LeetCode 加数字
- 面试题-堆和栈
- ArcObjects c++ 获取栅格或矢量图层的范围
- Reverse Nodes in k-Group
- Android PullToRefreshScrollView、AutoHeightListView、AutoScrollViewPager的使用
- PyQt + QtDesigner的ui文件
- XmlPullParser的使用
- Java进阶(二十七)使用Dom4j解析XML文件
- Android 手机号、身份证号、邮件,从view得到图片、去除html标签工具类