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;
    }
};
相关推荐
kyle~7 分钟前
原子性与原子操作
运维·服务器·开发语言·c++
前路不黑暗@13 分钟前
Java:继承与多态
java·开发语言·windows·经验分享·笔记·学习·学习方法
第七序章14 分钟前
【C + +】C++11 (下) | 类新功能 + STL 变化 + 包装器全解析
c语言·数据结构·c++·人工智能·哈希算法·1024程序员节
voice67014 分钟前
西电现代密码学实验一
开发语言·python·密码学
AA陈超25 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-29 属性信息委托
c++·游戏·ue5·游戏引擎·虚幻
Theodore_102232 分钟前
深度学习(10)模型评估、训练与选择
人工智能·深度学习·算法·机器学习·计算机视觉
五条凪37 分钟前
Verilog-Eval-v1基准测试集搭建指南
开发语言·人工智能·算法·语言模型
初学小白...38 分钟前
反射概述and获得反射对象
开发语言·python
是店小二呀1 小时前
从“算法思维”到“算子思维”:我在昇腾AI开发中的认知跃迁
人工智能·算法
后藤十八里1 小时前
2025python学习笔记Part2
开发语言·python