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;
    }
};
相关推荐
Java展博14 小时前
[Go 后端转场] 从 try-catch 到 if err != nil:写惯 Java 的人第一次上手最别扭的 4 件事
java·开发语言·golang
SEO_juper14 小时前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
风落青芜15 小时前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
H H.18 小时前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计
Pniubi19 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
吃我一窝jio1 天前
Python与Go线程模型深度对比
java·开发语言·python
文丑颜不良啊1 天前
LeetCode3041~3060题目解析
java·leetcode
eggwyw1 天前
C++ union 的一种妙用法
开发语言·c++
罗西的思考1 天前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊1 天前
LeetCode3101~3120题目解析
java·leetcode