成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LintCode] Add Digits

QiShare / 2029人閱讀

Problem

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example

Given num = 38.
The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return 2.

Challenge

Could you do it without any loop/recursion in O(1) runtime?

Solution
recursive
public class Solution {
    /*
     * @param num: a non-negative integer
     * @return: one digit
     */
    public int addDigits(int num) {
        // write your code here
        if (num < 10) return num;
        int sum = 0;
        while (num != 0) {
            sum += (num%10);
            num /= 10;
        }
        return addDigits(sum);
    }
}
Non-recursive
public class Solution {
    /*
     * @param num: a non-negative integer
     * @return: one digit
     */
    public int addDigits(int num) {
        // write your code here
        while (num >= 10) {
            String cur = Integer.toString(num);
            int sum = 0;
            for (int i = 0; i < cur.length(); i++) {
                sum += Character.getNumericValue(cur.charAt(i));
            }
            num = sum;
        }
        return num;
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/68260.html

相關(guān)文章

  • [LeetCode/LintCode] Plus One

    Problem Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. Example Given [1,2...

    sunsmell 評論0 收藏0
  • [LintCode] Big Integer Addition

    Problem Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Notice The length of both num1 and num2 is < 5100.Both num1 and num2 contains only digits ...

    i_garfileo 評論0 收藏0
  • [LintCode] Delete Digits [Greedy]

    摘要:題意為取刪去個字符后最小的值,仍以返回。所以無論刪除個元素之后的元素放入順序如何,此時棧內(nèi)元素從底到頂?shù)呐帕幸欢ㄊ菨M足條件的最小值。這種情況下,就要從堆棧頂部刪除剩下的兩個元素和然后,將棧內(nèi)的元素放入,并將頂部的全部去掉,然后以返回。 Problem Given string A representative a positive integer which has N digits,...

    張漢慶 評論0 收藏0
  • [LintCode/LeetCode] Add Two Numbers

    Problem You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1s digit is at the head of the list. Write a f...

    hedzr 評論0 收藏0
  • [LintCode] Print Numbers by Recursion

    摘要:只有當位數(shù)時,才打印數(shù)字。首先分析邊界,應(yīng)該,然后用存最高位。用函數(shù)對進行遞歸運算,同時更新結(jié)果數(shù)組。更新的過程歸納一下,首先,計算最高位存入,然后,用到倍的和之前里已經(jīng)存入的所有的數(shù)個循環(huán)相加,再存入,更新,計算更高位直到等于 Problem Print numbers from 1 to the largest number with N digits by recursion. ...

    kumfo 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<