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;
    }
};
相关推荐
码客-ygluu2 小时前
X3 LUA 异步分布式微服务集群框架
c++·架构·lua
starzy19903 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
M--Y4 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
forest_095 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
九英里路5 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
吴可可1235 小时前
WScript Shell操作注册表详解
开发语言
纪念 2296 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
文丑颜不良啊8 小时前
LeetCode2761~2780题目解析
java·leetcode
jyOverQ9 小时前
从零学 JVM(六):垃圾回收算法详解——标记清除、标记复制与标记整理
jvm·算法
码农小河6610 小时前
基于PHP的电商后台蜜罐系统
开发语言·php