My golang solution with comment (0ms)


  • 0
    C
    // plusone.go
    func PlusOne(digits []int) []int {
    	// add one more slot to head for convenient
    	digits = append([]int{0}, digits...)
    	for i := len(digits) - 1; i >= 0; i-- {
    		// find the first digit not 9 and plus one
    		if digits[i] != 9 {
    			digits[i] += 1
    			break
    		} else {
    			// otherwise set to 0
    			digits[i] = 0
    		}
    	}
    	// if the first digit is 0 return the rest of slice
    	if digits[0] == 0 {
    		return digits[1:]
    	}
    	return digits
    }
    

    And the related test file

    func TestPlusOne(t *testing.T) {
    	cases := []struct {
    		name   string
    		inputs []int
    		expect []int
    	}{
    		{"1 digit is zero", []int{0}, []int{1}},
    		{"1 digit is 9", []int{9}, []int{1, 0}},
    		{"2 normal digits", []int{2, 3}, []int{2, 4}},
    	}
    	for _, c := range cases {
    		t.Run(c.name, func(t *testing.T) {
    			ret := PlusOne(c.inputs)
    			if !reflect.DeepEqual(ret, c.expect) {
    				t.Fatalf("expected %v, but got %v, with inputs %v",
    					c.expect, ret, c.inputs)
    			}
    		})
    	}
    	t.Log("passed")
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.