美文网首页LeetCode By Go
[LeetCode By Go 23]258. Add Digi

[LeetCode By Go 23]258. Add Digi

作者: miltonsun | 来源:发表于2017-08-18 11:46 被阅读4次

    题目

    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 loop/recursion in O(1) runtime?

    解题思路

    循环累加每一位,时间复杂度O(logN)
    不需要循环,递归的暂时没想到,/(ㄒoㄒ)/~~

    代码

    addDigits.go

    package _258_Add_Digits
    
    func AddDigits(num int) int {
        for ;num >= 10; {
            var sum int
            for ;num >= 10; {
                sum += num % 10
                num = num / 10
            }
            num += sum
        }
    
        return num
    }
    

    测试

    addDigits_test.go

    package _258_Add_Digits
    
    import "testing"
    
    func TestAddDigits(t *testing.T) {
        var tests = []struct{
            num int
            output int
        }{
            {38, 2},
            {10, 1},
        }
    
        for _, test := range tests {
            ret := AddDigits(test.num)
    
            if ret == test.output {
                t.Logf("pass")
            } else {
                t.Errorf("fail, want %+v, get %+v", test.output, ret)
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 23]258. Add Digi

        本文链接:https://www.haomeiwen.com/subject/xctarxtx.html