LeetCode Add Digits (规律题)

题意:

  将一个整数num变成它的所有十进制位的和,重复操作,直到num的位数为1,返回num。

思路:

  规律在于随着所给自然数num的递增,结果也是在1~9内循环递增的,那么结果为(num-1)%9+1。注意num为0的情况。

1 class Solution {
2 public:
3     int addDigits(int num) {
4         if(!num)    return 0;
5         else    return (num-1)%9+1;
6     }
7 };

AC代码

时间: 2024-08-28 21:47:01

LeetCode Add Digits (规律题)的相关文章

[LeetCode] Add Digits (a New question added)

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up:Could you do it without any

[LeetCode] Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 分析一:最简单的循环方法 class Solution { public:

LeetCode——Add Digits

Description: Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up:Could you do i

[LeetCode] Add Digits 加数字

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without an

LeetCode Add Binary 结题报告

https://oj.leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 解题报告:二进制加法,分类为:Easy.没有任何算法,就是按照普通的方法计算即可. 一开始写了一个高低位reverse的,然后再从0到高位

我也来刷LeetCode——3、Add Digits

唉,做完这道题目后,有种羞愧无比的感觉,果然还是读书太少... 什么意思呢?就像这道题目一样,要求你编程计算出从1加到100的结果.于是你用循环从1累加到100,结果为5050.而大家都知道,从数学上的角度来解答,结果就是(a[1]+a[n])* n / 2. LeetCode上面的这道[Add Digits]题,其实是道数学题.它这个求解的结果,在数学上称为数根. 原题大概意思是这样,给定一个正整数,循环累加它的各位,直到结果为一位数.如 num 是38,计算的过程是 3+8=11,1+1=2

Leetcode刷题记录[python]——258 Add Digits

一.前言 做这题有个小收获,关于Digital root的解法,有个极方便的小公式: 二.题258 Add Digits Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. class Solution(object): def addDigits(self, num): """ :type num: int :rtype: i

leetcode 21_Merge Two Sorted Lists & leetcode_258 Add Digits & leetcode_66plus one

l leetcode 21_Merge Two Sorted Lists 题目:Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 解法: #include <iostream> using namespace std; struct ListNode { int

LeetCode:Add Digits - 非负整数各位相加

1.题目名称 Add Digits (非负整数各位相加) 2.题目地址 https://leetcode.com/problems/add-digits 3.题目内容 英文:Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 中文:有一个非负整数num,重复这样的操作:对该数字的各位数字求和,对这个和的各位数字再求和--直到最后得到一个仅1位的数字