Skip to content

Instantly share code, notes, and snippets.

@abdulrahmanAlotaibi
Created December 15, 2022 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdulrahmanAlotaibi/84c1c7aba33c91104e1e569004376e6e to your computer and use it in GitHub Desktop.
Save abdulrahmanAlotaibi/84c1c7aba33c91104e1e569004376e6e to your computer and use it in GitHub Desktop.
Array # 8 : Plus One
/*
You are given a large integer represented as an integer array digits,
where each digits[i] is the ith digit of the integer.
The digits are ordered from most significant to least significant in left-to-right order.
The large integer does not contain any leading 0's.
*/
func plusOne(digits []int) []int {
digitsStr := ""
for i:= 0 ; i < len(digits) ; i++ {
d := strconv.Itoa(digits[i])
digitsStr += d
}
// Digits constraints are >= 100 , so let's convert the string to big number
n:= new(big.Int)
n, ok := n.SetString(digitsStr, 0)
if !ok {
errors.New("Failed parsing string as big number")
}
one := big.NewInt(1)
newNumber := n.Add(n,one)
// Convert big int to string
newNumberStr := newNumber.String()
// Create the new digits arrays after it's being increamented
newDigits := []int{}
for _, numberStr := range newNumberStr {
// Conver rune to int
num, _ := strconv.Atoi(string(numberStr))
newDigits = append(newDigits, num)
}
return newDigits
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment