Leetcode#258. Add Digits (数字根)

声明:题目解法使用c++和Python两种,重点侧重在于解题思路和如何将c++代码转换为python代码。

题目

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)。

思路

前方高能注意,不能使用循环 or 递归。而且要求时间复杂度为O(1),暂时没有思路,看一下提示有没有有价值的信息。
这里写图片描述
前三条基本没用,最后一条:
You may find this Wikipedia article useful.
打开维基百科原来这是一道数字根的题目,用到的公式是同余式:
这里写图片描述
公式的文字意思:0的数字根为0,9的倍数的数字根为9,其他自然数的数字根为自然数除以9的余数。
上述公式也可以简单表述为:
自然数的数字根为自然数减去1除以9的余数加上1。
维基百科证明:https://en.wikipedia.org/wiki/Digital_root#Congruence_formula
所以,这道题就很好解决啦。

class Solution {
public:
    int addDigits(int num) 
    {
        /*公式一:
        if(num == 0)
            return 0;
        else if(num % 9 == 0)
            return 9;
        else 
            return (num)%9;
        */

        //公式二    
        return 1 + ((num - 1) % 9);
    }
};

Github本题题解:https://github.com/xuna123/LeetCode/blob/master/Leetcode%23258.%20Add%20Digits.md

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值