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;
    }
};
相关推荐
OOJO16 分钟前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
别或许2 小时前
1、高数----函数极限与连续(知识总结)
算法
派大星~课堂2 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
田梓燊2 小时前
code 560
数据结构·算法·哈希算法
笨笨饿2 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
kobesdu2 小时前
综合强度信息的激光雷达去拖尾算法解析和源码实现
算法·机器人·ros·slam·激光雷达
艾为电子2 小时前
【技术帖】让接口不再短命:艾为 C-Shielding™ Type-C智能水汽防护技术解析
c语言·开发语言
weixin_413063212 小时前
记录 MeshFlow-Online-Video-Stabilization 在线稳像
算法·meshflow·实时防抖
会编程的土豆3 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
棉花骑士3 小时前
【AI Agent】面向 Java 工程师的Claude Code Harness 学习指南
java·开发语言