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;
    }
};
相关推荐
2401_8914821711 分钟前
多平台UI框架C++开发
开发语言·c++·算法
88号技师33 分钟前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t1987512834 分钟前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神35 分钟前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
㓗冽1 小时前
8皇后·改-进阶题16
数据结构
m0_726965981 小时前
面面面,面面(1)
java·开发语言
x_xbx1 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor1 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920742 小时前
分布式系统安全通信
开发语言·c++·算法
~无忧花开~2 小时前
React状态管理完全指南
开发语言·前端·javascript·react.js·前端框架