string, swapping 0 and 1 in constant time

Viewed 32

Given a string consisting 0's and 1's, and an integer i, is there a way to change 0's to 1's and 1's to 0's up to index i in a constant time using binary number operations or something?

For example, if the input is "010101" and i=2, the output would be "101101"

Thank you so much for your help.

1 Answers

Try this

strArr = list("010101")

charReplaceObj = {
  "0": "1",
  "1": "0"
}

print "".join([ charReplaceObj[x] for x in strArr])

You can make this more dynamic by making it a function with parameters.

Related