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;
    }
};
相关推荐
房开民1 小时前
c++总结
java·开发语言·c++
好大哥呀1 小时前
C++ 多态
java·jvm·c++
毕设源码-赖学姐1 小时前
【开题答辩全过程】以 基于Java的医院器材管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
float_com1 小时前
【java常用API】----- Arrays
java·开发语言
不会写DN2 小时前
PHP 中的文件读写与上传
android·开发语言·php
阿豪学编程2 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
LuckyTHP3 小时前
迁移shibboleth java获取shibboleth用户信息
java·开发语言
墨韵流芳3 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
客卿1233 小时前
数论===质数统计(暴力法,)
java·开发语言
hz_zhangrl3 小时前
CCF-GESP 等级考试 2026年3月认证C++五级真题解析
c++·青少年编程·程序设计·gesp·c++五级·gesp2026年3月·gesp c++五级