4 ms·
The following is incorrect for finding a missing number in a sequence. func foo( _ nums: [Int] ) -> Int { var sum = 0 var _ = nums.map {sum += $0}
by seg12 8y ago
The following is incorrect for finding a missing number in a sequence.
func foo( _ nums: [Int] ) -> Int {
var sum = 0
var _ = nums.map {sum += $0}
return (nums.count * ((nums.count+1) / 2)) - sum
}
The last line should be
return ((nums.count+1) * ((nums.count+2) / 2)) - sum
The count of nums will give the incorrect answer since it's already missing a value.
- hadeon 8y agoYou're absolutely right, thanks for noticing this. There was also a bug with the parentheses I hadn't caught.