Created
December 5, 2017 03:48
-
-
Save khawajafarooq/cc5f76b4d787fc5158850f121312c4ea to your computer and use it in GitHub Desktop.
Add 1 number in an array - Geeks for geeks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Test Cases | |
Input: [1, 2, 3, 4] | |
Output: [1, 2, 3, 5] | |
Input: [1, 2, 9, 9] | |
Output: [1, 3, 0, 0] | |
Input: [9, 9, 9, 9] | |
Output: [1, 0, 0, 0] | |
Input: [] | |
Output: [1] | |
*/ | |
func addOneNumber(_ array: [Int]) -> [Int] { | |
// if empty input | |
if array.isEmpty { | |
return [1] | |
} | |
var carry = 1 | |
var result: [Int] = array.map { | |
let sum = $0 + carry | |
if sum == 10 { | |
carry = 1 | |
return 0 | |
} else { | |
carry = 0 | |
return sum | |
} | |
} | |
// Corner Case: | |
// if all of the values are 9 | |
if carry != 0 { | |
result.append(carry) | |
let lastIndex = result.count-1 | |
result.swapAt(0, lastIndex) | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment