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;
    }
};
相关推荐
(Charon)19 分钟前
【C++面试】线程并发与异步:区别、实现原理及使用场景
开发语言·c++
AIFQuant33 分钟前
Python A股实时行情API接入:沪深股票数据与WebSocket推送实战
开发语言·python·websocket·金融·a股行情
糖果豆豆39 分钟前
对象是字段,还是关系?集合论和范畴论吵了三十年,答案是两个都对
算法·架构
2302_8057710742 分钟前
Day23:POM设计模式(封装)
java·开发语言·设计模式
十年Java程序媛1 小时前
Java String、StringBuilder、StringBuffer 底层原理|字符串拼接性能与线程安全
java·开发语言·spring boot·安全·面试
Cx330❀1 小时前
Qt 界面美化指南:从零掌握 QSS 核心机制与工程实践
开发语言·qt·ui·性能优化·图形渲染
可乐ea1 小时前
2000 个智能体把 Agent 重写成 Rust:编排流水线拆解
开发语言·后端·rust·多智能体协作·ai编程助手·智能体编排·rust重写
JMchen1 小时前
实战项目一——实现一个高性能图片滤镜App
android·c++·性能优化
我是人✓1 小时前
SpringMVC异常处理与拦截器实战揭秘
java·开发语言·后端
第六种自由1 小时前
[路飞]_Leetcode 22. 括号生成
javascript·算法·leetcode