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;
    }
};
相关推荐
tang&3 小时前
【Python自动化测试】Selenium常用函数详解
开发语言·python·selenium
卜锦元3 小时前
Golang项目开发过程中好用的包整理归纳(附带不同包仓库地址)
开发语言·后端·golang
Tony Bai8 小时前
“我曾想付钱给 Google 去工作”—— Russ Cox 深度访谈:Go 的诞生、演进与未来
开发语言·后端·golang
sali-tec8 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java8 小时前
常见排序算法的实现
数据结构·算法·排序算法
45288655上山打老虎8 小时前
C++完美转发
java·jvm·c++
hnlgzb8 小时前
安卓app开发,如何快速上手kotlin和compose的开发?
android·开发语言·kotlin
行云流水20198 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
无敌最俊朗@9 小时前
STL-deque面试剖析(面试复习4)
开发语言
APIshop9 小时前
用 Python 把“API 接口”当数据源——从找口子到落库的全流程实战
开发语言·python