Interview Question
Country: United States
Let's keep this example at 8 bits for simplicity.
Let's start with our sample input: input = 10101010
Create another number i which will start at 1: i = 00000001
Shift it k times. (Let's say k = 3): i = 00001000
Negate it with XOR by performing i ^ Int.max: i = i ^ 11111111 = 11110111
Return i & number: 10100010
Swift 2.2
func flip(k: Int, number:Int) -> String {
var operand = 1
operand = operand << k
operand = operand ^ Int.max
return String(operand & number, radix: 2)
}
flip(0, number: 0b101) // "100"
flip(1, number: 0b101) // "101"
flip(2, number: 0b101) // "1"
(n & (1 << k)) ? (n ^ (1 << k)) : n
- Nisheeth August 08, 2016