Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Created September 26, 2019 00:28
Show Gist options
  • Save jakehawken/a94e5cf38b39b11d3997d146aac33a9f to your computer and use it in GitHub Desktop.
Save jakehawken/a94e5cf38b39b11d3997d146aac33a9f to your computer and use it in GitHub Desktop.
Leetcode #66: "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."
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
guard !digits.isEmpty else {
fatalError("But you promised!")
}
var digits = digits
let lastIndex = digits.count - 1
for i in 0...lastIndex {
let index = lastIndex - i
var digit = digits[index]
if digit != 9 {
digit += 1
digits[index] = digit
break
}
else {
digits[index] = 0
if index == 0 {
digits.insert(1, at: 0)
}
}
}
return digits
}
}
/*
Leetcode results:
------------------------------------------------------------------------------
Runtime: 8 ms, faster than 78.25% of Swift online submissions for Plus One.
Memory Usage: 21 MB, less than 20.00% of Swift online submissions for Plus One.
-------------------------------------------------------------------------------
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment