258. Add Digits

原题链接:https://leetcode.com/problemset/algorithms/
题目:
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.

题意:给你一个数字,要求你把各个位上的数字分别相加,如果结果大于两位,则重复操作,直到结果是个位数,把结果返回。
另外:题目跟进让我们试着写一种没有循环和递归的时间复杂度位O(1) 的解法。

解法思路一: 在无视跟进的情况下,用一个递归把各位数相加即可

时间复杂度位O(1) 的解法思路:
因为若num=a*1000+b*100+c*10+d;
则num=a+b+c+d+( a*999+b*99+c*9),
所以 num%9==(a+b+c+d)%9, 而a+b+c+d 要变成一个大于等于1并且小于等于9的数字,
要防止a+b+c+d==9的情况下num%9==0,所以应事先对 a+b+c+d 减去1,再取模 ,而事后要加 1
所以所求数字应是 (num-1)%9+1

解法一的ac代码:

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

时间复杂度位O(1) 的ac代码:

class Solution {
public:
    int addDigits(int num) {
        return (num - 1) % 9 + 1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值