'In Swift, why does a bitwise NOT require adding one to get a positive integer's corresponding negative integer?

For example,

func challenge26c(subtract: Int, from: Int) -> Int {
    return from + (~subtract + 1)
}

Does the same apply in other programming environments?



Solution 1:[1]

This is due to how integers are stored in Swift (and in almost every case I can think of), in what is called two's complement notation. If you want a "positive integer's corresponding negative integer" (known mathematically as the additive inverse), you can simply use the unary minus sign - (for example, if x is 5, then -x becomes -5.

It looks to me like this is a challenge to implement subtraction without using -, though, so you probably will want to read up on two's complement notation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sam