Skip to content

Instantly share code, notes, and snippets.

@mrhm-dev
Created April 10, 2022 17:27
Show Gist options
  • Save mrhm-dev/3086a72336494de19e7f653a5fb28e81 to your computer and use it in GitHub Desktop.
Save mrhm-dev/3086a72336494de19e7f653a5fb28e81 to your computer and use it in GitHub Desktop.
// Recursive One
func plusOne(digits []int) []int {
lastIndex := len(digits) - 1
n := digits[lastIndex] + 1
if (n < 10) {
digits[lastIndex] = n
return digits
}
r := n / 10
n = n % 10
digits[lastIndex] = n
return plusOneRecursive(digits, lastIndex-1, r)
}
func plusOneRecursive(digits []int, lastIndex int, r int) []int {
if lastIndex < 0 {
fmt.Println(lastIndex, r)
if r != 0 {
digits = append([]int{r}, digits... )
}
return digits
}
n := digits[lastIndex] + r
if n < 10 {
digits[lastIndex] = n
return digits
}
remainder := n / 10
newN := n % 10
digits[lastIndex] = newN
return plusOneRecursive(digits, lastIndex-1, remainder)
}
// Loop
func plusOne(digits []int) []int {
carry := 1
for i:=len(digits)-1; i>=0; i-- {
sum := carry + digits[i]
if sum <= 9 {
digits[i] = sum
carry = 0
break
}
digits[i] = sum - 10
carry = 1
}
if carry == 1 {
digits = append([]int{1}, digits...)
}
return digits
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment