[LeetCode][JavaScript]Add Digits
2015-08-17 00:11
609 查看
Add Digits
Given a non-negative integernum, 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
2has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.
数学题给跪了。
如果可以用循环,最好的情况是只读一遍。
贪心,每读一数都做Digit Root的操作,最后的结果是正确的。
/** * @param {number} num * @return {number} */ var addDigits = function(num) { var str = num.toString(), res = 0, tmp1, tmp2; for(var i = 0; i < str.length; i++){ res = parseInt(str[i]) + res; if(res >= 10){ tmp1 = parseInt(res / 10); tmp2 = res % 10; res = tmp1 + tmp2; } } return res; };
最佳答案参照wiki : https://en.wikipedia.org/wiki/Digital_root
好几种写法都可以,这里列了2种。
/** * @param {number} num * @return {number} */ var addDigits = function(num) { return num === 0 ? 0 : num - 9 * Math.floor((num - 1) / 9); };
/** * @param {number} num * @return {number} */ var addDigits = function(num) { return 1 + (num - 1) % 9; };
相关文章推荐
- 关于js里的this关键字的理解
- D3.js中data(), enter() 和 exit()的问题详解
- js实现的全国省市二级联动下拉选择菜单完整实例
- js简单实现Select互换数据的方法
- JS实现的5级联动Select下拉选择框实例
- JavaScript判断表单中多选框checkbox选中个数的方法
- js下拉选择框与输入框联动实现添加选中值到输入框的方法
- js实现表单Radio切换效果的方法
- js实现匹配时换色的输入提示特效代码
- JS模仿编辑器实时改变文本框宽度和高度大小的方法
- js实现浏览本地文件并显示扩展名的方法
- js实现Select头像选择实时预览代码
- JStorm中的并行( parallelismction )介绍
- JavaScript中的this陷阱的最全收集
- com.alibaba.fastjson.JSONException: create instanc
- JStorm中消息确保处理机制
- Sea.js
- JStorm/Strom配置executors和tasks(线程和实例)
- 第二篇 arcgis api for js 根据坐标生成点
- IPv4地址与整型类型互转_Java_PHP_JavaScript