Xiaohe-LeetCode 258 Add Digit

This is not the best one.

public class Solution {
  public int addDigits(int num) {
    if(num<10)
      return num;
    int sum=0;
    while(num>=10)
    {
      sum=sum+num%10;
      num=(num-num%10)/10;
    }
    sum=sum+num;
    if(sum<10)
      return sum;
    else
    return addDigits(sum);
  }
}

时间: 2024-08-24 17:58:30

Xiaohe-LeetCode 258 Add Digit的相关文章

[leetcode] 258. 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 any

Java [Leetcode 258]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. 解题思路: 假设输入的数字是一个5位数字num,则num的各位

leetcode 258. 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. 这道题是求一个数的数根. 数根有一个同余性质:一个数与它的数根对(b-1)

(easy)LeetCode 258.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 any

leetcode 258 Add Digits数论

1 class Solution { 2 public: 3 int addDigits(int num) { 4 if(num == 0 ) return num; 5 else return num % 9 == 0 ? 9 : num % 9; 6 } 7 }; 就是数位根!

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位的数字

leetCode 258 AddDigits

leetcode 258 Add Digits 题目翻译: 给出一个非负整数num,不断地把它所有数字相加,直到最后剩下一个数字. 例如:num=38,计算过程如,3+8=11,1+1=2,所以2就是最后的数字,返回它就可以了. 并且,你能不使用任何循环或者递归,在O(1)的复杂度内完成吗? 解题思路: 时间复杂度规定了在O(1)内完成,不能采用循环或者递归,那么就变成了数学的问题了,必须找到一个类似方程式的函数,带入即可求解.然后,偶然发现对于9的倍数的一个规律:18,27,36,...,81

LeetCode No.258 Add Digits

LeetCode  Algorithum # title solution difficulty 258  Add Digits  java  easy         NO.258 (2015.10.26 16:09:00) Given a non-negative integer num,repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the pro

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