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;
    }
};
相关推荐
小七在进步8 分钟前
C++入门(2)
java·jvm·c++
en.en..36 分钟前
C语言核心解析:#define与typedef本质区别
开发语言·c++·算法
2601_9669496543 分钟前
批量获取多只股票五档盘口的极简方案:QuantDash Python SDK 实战指南
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
码匠许师傅1 小时前
【设计模式精讲】26.策略模式(Strategy)
c++·设计模式·策略模式·uml
点心的游戏开发世界2 小时前
GDScript 入门笔记:目录
开发语言·笔记·游戏引擎·godot
洋不写bug2 小时前
二叉树(二) 常见基础操作解析|结点数、树高、查找结点、判断完全二叉树
java·开发语言·数据结构·完全二叉树·二叉树结点数·树高·查找结点
果果燕2 小时前
实习笔记(六)主机按钮状态上报完整流程
开发语言·c++·php
化雨成烟2 小时前
C++之AVL树
数据结构
平头哥技术团队2 小时前
Day 16 | 用 ul、ol、li 一个标签,把散资料收成有序的技能清单页
开发语言·前端·html·html5
是个西兰花2 小时前
网络基础1
linux·网络·c++·智能路由器