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;
    }
};
相关推荐
许长安2 分钟前
RPC 异步调用基本使用方法:基于官方helloworld-async 示例
c++·经验分享·笔记·rpc
Chase_______32 分钟前
LeetCode 2461 & 1423:定长滑窗变体精讲,从 HashMap 判重到正难则反的转化技巧
算法·leetcode·职场和发展
摇滚侠38 分钟前
软件开发外包项目组,如何提高代码质量和开发效率
java·开发语言·前端·ide·intellij-idea
sparEE41 分钟前
c++面向对象:对象的赋值
开发语言·c++
此生决int1 小时前
快速复习之数据结构篇——栈和队列
数据结构·c++
WL_Aurora1 小时前
【每日一题】二分算法
python·算法
昵称小白1 小时前
子串专题部分
数据结构·算法·哈希算法
H_BB1 小时前
第17届蓝桥杯备战历程
c++·算法·职场和发展·蓝桥杯
threelab1 小时前
Three.js 图像粒子飞线效果 | 三维可视化 / AI 提示词
开发语言·javascript·人工智能