Home > front end >  In Swift, why does a bitwise NOT require adding one to get a positive integer's corresponding n
In Swift, why does a bitwise NOT require adding one to get a positive integer's corresponding n

Time:04-05

For example,

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

Does the same apply in other programming environments?

CodePudding user response:

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.

  • Related