Leetcode - Move Zeroes
Leetcode - Merge Sorted Array

Leetcode - Plus One

violet posted @ Mar 30, 2020 06:38:04 AM in 算法 with tags Algorithm Golang array , 213 阅读

https://leetcode.com/problems/plus-one

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

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

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

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

 

The only problem is carry. No big deal.

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

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter