leetcode:66. Plus One

2018-08-22  本文已影响0人  唐僧取经

66. Plus One

Description

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.
Example 2:

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

解题思路:注意审题,是每个元素都只包含一个数字 ‘a’,我读题的时候,就会错了题意

1.从后往前遍历
2.每个元素+1,如果结果大于等于10,则该位置为0
3.进位1(此时的处理是,让循环继续进行+一次),以便判断每一位数字,依次继续下去
4.中途有不需要进位的,就返回return
5.如果一直进位,则在最前面补1

Answer

package main

import "fmt"

func plusOne(digits []int) []int {
    for i := len(digits) - 1; i >= 0; i-- {
        digits[i] += 1
        if digits[i] >= 10 {
            digits[i] = 0
        } else {
            return digits
        }
    }

    digits = append([]int{1}, digits...)
    return digits

}

func main() {
    fmt.Println(plusOne([]int{8, 9, 9}))
}


上一篇 下一篇

猜你喜欢

热点阅读