美文网首页LeetCode By Go
[LeetCode By Go 84]66. Plus One

[LeetCode By Go 84]66. Plus One

作者: miltonsun | 来源:发表于2017-09-04 14:09 被阅读10次

    题目

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.

    解题思路

    用一个0-9的数字组成的数组代表一个正整数,将这个正整数加1
    个位加1后,需要从个位开始逆序遍历这个数组,更新每一位的值,注意进位

    代码

    func plusOne(digits []int) []int {
        len1 := len(digits)
    
        digits[len1 - 1] = digits[len1 - 1] + 1
        var carry int
        if digits[len1 - 1] == 10 {
            carry = 1
            digits[len1 - 1] = 0
        }
    
    
        for i := len1-2; i >= 0; i-- {
            digits[i] = carry + digits[i]
            if digits[i] == 10 {
                digits[i] = 0
                carry = 1
            } else {
                carry = 0
            }
        }
    
        if carry == 1 {
            var ret []int
            ret = append([]int{carry}, digits...)
            return ret
        } else {
            return digits
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 84]66. Plus One

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