LeetCode 258 Add Digits
leetcode 上做了一题比较有意思,记录一下,传送门:https://leetcode.com/problems/add-digits/description/
题目意思是:给一个正整数a,让其个位,十位,百位·····一直到最高位加起来得到另一个数字b,然后再对数字b重复这个过程,直到相加的到的数字为个位数时返回
举例说明:
例如输入234,返回值为2+3+4=9
输入78,第一步7+8=15,第二步1+5=6,返回6
多试几个发现有以下规律
输入 | 输出 |
29 | 2 |
28 | 1 |
27 | 9 |
26 | 8 |
25 | 7 |
24 | 6 |
23 | 5 |
22 | 4 |
21 | 3 |
20 | 2 |
······ | ······· |
发现输出的数为输入数字的取余(9的倍数和小于9的数字除外)
验证也不难,推导过程如下:
假设输入数字为num,可将num拆分为个位数字乘以1,十位数字乘以十,百位数字乘以100,以此类推到最高位,
数学表达式表示为:input=n1*1+n2*10+n3*100+·····(n1,n2,n3···分别表示个位数字,十位数字,百位数字····)
执行一次之后:ouput=n1+n2+n3+·····(n1,n2,n3···分别表示个位数字,十位数字,百位数字····)
input - output = 9 * (1/9 * n1+n2+11*n3+111*n4+·········)=9*sum(sum为一个常量)
所以最后的代码为(javascript):
var addDigits = function(num) {if(num<9) return num;if(num%9===0) return 9;return num%9;
};
转载于:https://www.cnblogs.com/xingguozhiming/p/9386154.html
LeetCode 258 Add Digits相关推荐
- LeetCode 258. Add Digits
题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one di ...
- Leetcode刷题记录[python]——258 Add Digits
一.前言 做这题有个小收获,关于Digital root的解法,有个极方便的小公式: 二.题258 Add Digits Given a non-negative integer num, repea ...
- 【leetcode】258. Add Digits
题目如下: 解题思路:题目很简单,没啥说的.Follow up 我还没想出来. 代码如下: class Solution(object):def addDigits(self, num):" ...
- [leetcode][math] Add Digits
题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one di ...
- Leet Code OJ 258. Add Digits [Difficulty: Easy]
题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one di ...
- LeetCode之Add Digits
1.题目 Given a non-negative integer num, repeatedly add all its digits until the result has only one d ...
- 258. Add Digits
- leetcode Add Digits
题目连接 https://leetcode.com/problems/add-digits/ Add Digits Description Given a non-negative integer n ...
- LeetCode之Add Two Numbers
LeetCode之Add Two Numbers 题目:You are given two linked lists representing two non-negative numbers. Th ...
最新文章
- 彻底疯了,要给雷锋开博客?
- NPOI 导入Excel和读取Excel
- 根据txt中的文件名将文件复制到目标文件夹中
- linux_unix系统编程手册源代码编译
- 主存地址位数怎么算_两位数乘一位数也能口算?对!你没看错,不是特殊情况也行...
- 接口安全--签名验证
- 记录一次iOS11大标题不滚动的问题
- 用 Python 将 QQ 好友头像生成祝福语
- Linux GDB Debugging
- 计算机综合布线毕业论文设计方案,网络综合布线毕业论文设计.doc
- 无痛学习ISAC(一)
- 五险一金及个税计算器
- ios和android下数字没有垂直居中,手机端设置小号字体的上下居中问题
- 晶体(crystal)和晶振(oscillator)的区别
- sin30的c语言表达式,c语言sin30怎么写
- VsCode+OpenOCD 开发stm32系列
- NVIDIA BERT推理解决方案Faster Transformer开源了!
- vue 移动端H5微信支付和支付宝支付
- 工作四年,分享15个对Java 程序员有用的库
- WebForm(二)——控件和数据库连接方式