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;
    }
};
相关推荐
0xDevNull4 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
小小亮014 小时前
Next.js基础
开发语言·前端·javascript
ALex_zry4 小时前
C++网络编程心跳机制与连接保活:长连接稳定性保障
开发语言·网络·c++
Amumu121384 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
学嵌入式的小杨同学5 小时前
STM32 进阶封神之路(三十二):SPI 通信深度实战 —— 硬件 SPI 驱动 W25Q64 闪存(底层时序 + 寄存器配置 + 读写封装)
c++·stm32·单片机·嵌入式硬件·mcu·架构·硬件架构
米粒15 小时前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
Sgf2275 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
好大哥呀5 小时前
C++ Web 编程
开发语言·前端·c++
ID_180079054735 小时前
小红书笔记评论 API,Python 调用示例与完整 JSON 返回参考
java·开发语言
Fuxiao___5 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#