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;
    }
};
相关推荐
honiiiiii8 分钟前
SMU winter week4
c++
踩坑记录25 分钟前
递归回溯本质
leetcode
zmzb010333 分钟前
C++课后习题训练记录Day105
开发语言·c++·算法
wjs202434 分钟前
Vue3 条件语句
开发语言
_codemonster35 分钟前
JavaWeb开发系列(六)JSP基础
java·开发语言
闻缺陷则喜何志丹1 小时前
【拆位法】P8743 [蓝桥杯 2021 省 A] 异或数列|普及+
c++·蓝桥杯·位运算·拆位法
好学且牛逼的马1 小时前
【Hot100|25-LeetCode 142. 环形链表 II - 完整解法详解】
算法·leetcode·链表
fpcc1 小时前
跟我学C++中级篇——Concepts的循环依赖
c++·模板和元编程
Web打印1 小时前
Phpask(php集成环境)之16 怎样彻底停用一个网站
开发语言·php
临水逸1 小时前
飞牛fnos 2025 漏洞Java跨域URL浏览器
java·开发语言·安全·web安全