Hacker News new | ask | show | jobs
by seg12 2792 days 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.
1 comments

You're absolutely right, thanks for noticing this. There was also a bug with the parentheses I hadn't caught.