LeetCode //C - 258. Add Digits

258. 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 < = n u m < = 2 31 − 1 0 <= num <= 2^{31} - 1 0<=num<=231−1

From: LeetCode

Link: 258. Add Digits


Solution:

Ideas:

1. Digital Root Concept: The digital root of a number is the single-digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration. The digital root can be directly calculated using the formula:

  • If num == 0, then the digital root is 0.
  • If num % 9 == 0, then the digital root is 9 (except when num is 0).
  • Otherwise, the digital root is num % 9.

2. Mathematical Insight:

  • The digital root of a non-zero number is 1 + (num - 1) % 9, which simplifies to the above formula in the code.

3. Code Explanation:

  • If num is 0, return 0.
  • Otherwise, check if num % 9 == 0. If true, return 9 because the number is divisible by 9 and non-zero.
  • If num % 9 != 0, return num % 9.
Code:
c 复制代码
int addDigits(int num) {
    if (num == 0) return 0;
    return (num % 9 == 0) ? 9 : (num % 9);
}
相关推荐
智者知已应修善业17 分钟前
【51单片机用数码管显示流水灯的种类是按钮控制数码管加一和流水灯】2022-6-14
c语言·经验分享·笔记·单片机·嵌入式硬件·51单片机
拓端研究室1 小时前
视频讲解:门槛效应模型Threshold Effect分析数字金融指数与消费结构数据
前端·算法
随缘而动,随遇而安3 小时前
第八十八篇 大数据中的递归算法:从俄罗斯套娃到分布式计算的奇妙之旅
大数据·数据结构·算法
IT古董4 小时前
【第二章:机器学习与神经网络概述】03.类算法理论与实践-(3)决策树分类器
神经网络·算法·机器学习
Alfred king6 小时前
面试150 生命游戏
leetcode·游戏·面试·数组
水木兰亭7 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
Jess078 小时前
插入排序的简单介绍
数据结构·算法·排序算法
老一岁8 小时前
选择排序算法详解
数据结构·算法·排序算法
xindafu8 小时前
代码随想录算法训练营第四十二天|动态规划part9
算法·动态规划
xindafu8 小时前
代码随想录算法训练营第四十五天|动态规划part12
算法·动态规划