Leetcode#258. Add Digits (数字根)

来源:互联网 发布:淘宝上伊芙丽假货多吗 编辑:程序博客网 时间:2024/06/11 21:51

声明:题目解法使用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

原创粉丝点击