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 小时前
安装 Python 3.10+
开发语言·人工智能·python
KaMeidebaby2 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
8Qi83 小时前
LeetCode 235. 二叉搜索树的最近公共祖先(LCA)
算法·leetcode·二叉树·递归·二叉搜索树·lca·迭代
好评1243 小时前
【C++】智能指针全解
c++·智能指针
AAA大运重卡何师傅(专跑国道)3 小时前
【无标题】
开发语言·c#
bIo7lyA8v3 小时前
算法稳定性分析中的随机扰动建模的技术8
算法
是阿建吖!3 小时前
【Linux】信号
android·linux·c语言·c++
城北徐宫3 小时前
Linux信号深度解剖:5种产生、3张表、4次切换
linux·c++·学习
sugar__salt3 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
liulilittle3 小时前
论 Linux 内核态全局稳态带宽的卡尔曼估计与工程实现
linux·服务器·网络·c++·计算机网络·tcp·通信