leetcode算法——258:Add Digits(基于JAVA)
来源:互联网 发布:linux支持哪些文件系统 编辑:程序博客网 时间:2024/05/18 02:28
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?
翻译:
给定一个正数,将其所有位数上的数字进行相加得到一个新的数。不断反复,直到得到的数是一位数的。
优化:你能做到没有任何循环/递归在O(1)运行时?
解题思路:
首先要要能得出答案,再考虑优化的提议
1.先要保存好num各位上的数字
2.将保持好的数字进行相加得到新的num
3.反复操作,直到num满足只有一位数的要求
最后百度了发现还有一个更简单的方法,就是找规律。
1.while循环
int addDigits(int num) { int tem=0; while((num/10)>0) { while((num/10)>0) //遍历num每位的数字 { tem+= num%10; //得出num各位上的数字后直接相加 num=num/10; } num+=tem; tem=0; } return num;}
2.递归
public int addDigits(int num) { if (num < 10) { return num; } int res = 0; while (num > 0) { res += num % 10; num = num / 10; } return addDigits(res); }
3.找规律
input01234567891011121314151617181920output012345678912345678912表格有点丑,凑合看。
规律:除了第一个数字0外,呈现从1~9循环的规律。
这个方法还是借鉴别人的。反正我是想不到可以这么整,先学习了。
public int addDigits(int num) { return (num - 1) % 9 + 1; }
0 0
- leetcode算法——258:Add Digits(基于JAVA)
- leetcode 258 Add Digits(java)
- LeetCode 258 Add Digits java
- LeetCode 258 -Add Digits ( JAVA )
- [LeetCode-258]Add Digits(java)
- LeetCode[258]——Add Digits
- 【Leetcode算法】-Add Digits
- 【leetcode】Add Digits【java】
- (java) leetcode Add Digits
- leetcode:Add Digits 【Java】
- leetcode 258: Add Digits
- 258Add 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
- I/O多路转接之epoll
- Dubbo服务 初学配置
- Java中Object类的equals()和hashCode()方法
- c# 把excel表格当做数据库的使用感受
- SCPPO(十五):IIS配置文件节点加密
- leetcode算法——258:Add Digits(基于JAVA)
- 利用ObjectAnimator编写弹出式二级菜单
- ajax父页面main.html
- 1024: 个位数统计
- 图象处理基本算法[整理]
- 同时上传图片与文字
- 基于Token的WEB后台认证机制
- DOS初体验
- MSP430 一种低功耗设计