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 分钟前
杰理项目开发大全课程
人工智能·深度学习·算法
饭小猿人5 分钟前
Flutter实现底部动画弹窗有两种方式
开发语言·前端·flutter
aq553560017 分钟前
Workstation神技:一键克隆调试环境
java·开发语言
宏笋23 分钟前
C++11完美转发的作用和用法
c++
格发许可优化管理系统26 分钟前
MathCAD许可类型全面解析:选择最适合您的许可证
c++
风一样的航哥32 分钟前
LeetCode 2615 等值距离和:前缀和优化O(n)解法深度解析
数据结构·算法·leetcode
lly20240636 分钟前
框架:构建高效系统的基石
开发语言
生成论实验室1 小时前
生成态势猜想:一种统一的宇宙动力学语法
人工智能·科技·神经网络·算法·信息与通信
skywalk81631 小时前
发现Kotti项目的python包Beaker 存在安全漏洞
开发语言·网络·python·安全
旖-旎1 小时前
深搜(二叉树的所有路径)(6)
c++·算法·leetcode·深度优先·递归