LeetCode258. Add Digits

文章目录

一、题目

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Example 1:

Input: num = 38

Output: 2

Explanation: The process is

38 --> 3 + 8 --> 11

11 --> 1 + 1 --> 2

Since 2 has only one digit, return it.

Example 2:

Input: num = 0

Output: 0

Constraints:

0 <= num <= 231 - 1

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

二、题解

cpp 复制代码
class Solution {
public:
    int addDigits(int num) {
        while(num > 9){
            int sum = 0;
            while(num){
                sum += num % 10;
                num /= 10;
            }
            num = sum;
        }
        return num;
    }
};
相关推荐
Дерек的学习记录3 小时前
C++:stack和queue
开发语言·c++·学习·算法
烟烟Abandon4 小时前
FFmpeg开发基础之 C 语言 :再论指针(讲透指针)
c语言·开发语言·ffmpeg
风中的微尘7 小时前
数学基础2
算法
阿俊-全栈开发7 小时前
扩展设计解析:LikeShop Go 版商城营销活动的插件化扩展设计思路
开发语言·微服务·golang·likeshop·likeshop源码
干啥啥不行,bug第一名7 小时前
EAFNOSUPPORT、EPROTOTYPE、EOPNOTSUPP:socket 的三层参数没有对齐
开发语言·php
fqbqrr8 小时前
2612,现代cmake
c++·cmake
一只小小的芙厨8 小时前
树状数组总结
数据结构·算法
我要见SA姐18 小时前
用生活化类比当钥匙,一键打开 C++ 入门大门
java·开发语言·c++
1024奇点9 小时前
第四篇 第 03 课
开发语言·ide·后端
船神丿男人9 小时前
C++ 背包动态规划六题:看懂倒序、正序和两层循环
c++·动态规划