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相关推荐

  1. LeetCode 258. Add Digits

    题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one di ...

  2. Leetcode刷题记录[python]——258 Add Digits

    一.前言 做这题有个小收获,关于Digital root的解法,有个极方便的小公式: 二.题258 Add Digits Given a non-negative integer num, repea ...

  3. 【leetcode】258. Add Digits

    题目如下: 解题思路:题目很简单,没啥说的.Follow up 我还没想出来. 代码如下: class Solution(object):def addDigits(self, num):" ...

  4. [leetcode][math] Add Digits

    题目: Given a non-negative integer num, repeatedly add all its digits until the result has only one di ...

  5. 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 ...

  6. LeetCode之Add Digits

    1.题目 Given a non-negative integer num, repeatedly add all its digits until the result has only one d ...

  7. 258. Add Digits

  8. leetcode Add Digits

    题目连接 https://leetcode.com/problems/add-digits/ Add Digits Description Given a non-negative integer n ...

  9. LeetCode之Add Two Numbers

    LeetCode之Add Two Numbers 题目:You are given two linked lists representing two non-negative numbers. Th ...

最新文章

  1. 彻底疯了,要给雷锋开博客?
  2. NPOI 导入Excel和读取Excel
  3. 根据txt中的文件名将文件复制到目标文件夹中
  4. linux_unix系统编程手册源代码编译
  5. 主存地址位数怎么算_两位数乘一位数也能口算?对!你没看错,不是特殊情况也行...
  6. 接口安全--签名验证
  7. 记录一次iOS11大标题不滚动的问题
  8. 用 Python 将 QQ 好友头像生成祝福语
  9. Linux GDB Debugging
  10. 计算机综合布线毕业论文设计方案,网络综合布线毕业论文设计.doc
  11. 无痛学习ISAC(一)
  12. 五险一金及个税计算器
  13. ios和android下数字没有垂直居中,手机端设置小号字体的上下居中问题
  14. 晶体(crystal)和晶振(oscillator)的区别
  15. sin30的c语言表达式,c语言sin30怎么写
  16. VsCode+OpenOCD 开发stm32系列
  17. NVIDIA BERT推理解决方案Faster Transformer开源了!
  18. vue 移动端H5微信支付和支付宝支付
  19. 工作四年,分享15个对Java 程序员有用的库
  20. WebForm(二)——控件和数据库连接方式

热门文章

  1. 使用pycharm配置flask项目,并使用git进行版本控制
  2. 从包中构建瓦片服务器
  3. 【电路补习笔记】4、二极管的参数与选型
  4. 小米手机Linux Deploy安装Ubuntu
  5. 成功驱动HD4600-Clover引导
  6. linux kill 关闭进程命令
  7. 求一个正整数是由哪几个连数(连续的正整数)相加
  8. chrome浏览器的跨域设置,前端修改跨域问题
  9. react学习(62)--注意数据格式返回
  10. 前端学习(3190):react简介二