前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LintCode Add Digits分析代码

LintCode Add Digits分析代码

作者头像
desperate633
发布2018-08-22 15:41:29
2010
发布2018-08-22 15:41:29
举报
文章被收录于专栏:desperate633desperate633

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

样例 Given num = 38. The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return 2.

分析

首先:12345 = 1 * 9999 + 2 * 999 + 3 * 99 + 4 * 9

  • 5 + (1+ 2+ 3 + 4 + 5)只要证明:12345 % 9 = (1 + 2 + 3 + 4 +5 ) % 9 就能往下递推了。那么,我们已知:m % 9 = a; n % 9 = b 即 m = 9 * x + a; n = 9 * y + b;可推出 (m + n) % 9 = a + b = m % 9 + n % 9;[1 * 9999 + 2 * 999 + 3 * 99 + 4 * 9 + (1+ 2+ 3 + 4 + 5)] % 9 = (1 * 9999) % 9 + (2 * 999) % 9 + (3 * 99) % 9 + (4 * 9) % 9 + (1+ 2+ 3 + 4 + 5) % 9 = 0 + 0 + 0 + 0 + (1 + 2 + 3 + 4 + 5) % 9 = (1 + 2 + 3 + 4 + 5) % 9。证明完成:12345 % 9 = (1 + 2 + 3 + 4 + 5) % 9 ;

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param num a non-negative integer
     * @return one digit
     */
    public int addDigits(int num) {
         return (num - 1) % 9 + 1;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.03.24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档