【leetcode】【c++】258. add digits

本文探讨了给定一个非负整数,如何通过反复累加其各个位数直至结果为单个数字的算法。介绍了三种方法:递归+循环、纯循环及数学技巧法,并深入解析了数学技巧法背后的原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目介绍:

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

Example:

Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 111 + 1 = 2 Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

题目要求给定一个整数,将它的各位进行相加,如果和为一个个位数,那么输出,否则继续进行各位的相加。

首先注意到 如果给定一个特别大的数接近于 maxint , 请款将会变得非常的复杂,无论是用数组进行存储都会出现很多的问题,然而实际这种请款是不会出现的,因为要想得到一个个位数,最后相加的结果只能是一个个位数,即不超过10,说明给的数应当比较的小。

方法一:

按照递归 + 循环的方法进行解决:

class Solution {
public:
    int addDigits(int num) {
       if(num < 10)
           return num;
        int sum = 0;
        while(num > 0)
        {
            sum += num % 10;
            num /= 10;
        }
        return addDigits(sum);
    }
};

方法很容易理解,不做详细描述,递归是可以调用自己的。

方法二:

只用到循环:

class Solution {
public:
    int addDigits(int num) {
       while(num >= 10)
       {
           int sum = 0;
           while(num > 0)
           {
               sum += num % 10;
               num /= 10;
           }
           num = sum;
       }
        return num;
    }
};

以上 2 种方法的效率基本相同。

方法三:

尝试使用数学技巧进行问题的求解,代码为:

class Solution {
public:
    int addDigits(int num) {
        if(num < 10)
            return num;
        return ((num -1) % 9 + 1);
    }
};

 代码解释:

例如一个2位数 ab = a * 10 + b,  则 ab % 9 = (a * 9 + a + b)% 9 = (a + b) % 9 ;

3位数 abc = a * 100 + b * 10 + c ,则 abc % 9 = (a * 99 + b * 9 + a+ b + c) % 9 = (a + b + c) % 9;

用上面的规律,38 % 9 = 11% 9 = 2 % 9 = 2; 这与题目要求的方法完全一致,为了当 num = 9 时,返回的结果是 9 而不是 0,可以用(num - 1 ) % 9 + 1 去解决, ( 9 - 1 ) % 9 + 1 = 9 ,完全一致,问题得到解决。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值