## Friday, September 16, 2016

### Change if all bits can be made same by single flip - GeeksforGeeks

Change if all bits can be made same by single flip - GeeksforGeeks
Given a binary string, find if it is possible to make all its digits equal (either all 0's or all 1's) by flipping exactly one bit.

If all digits of a string can be made identical by doing exactly one flip, that means the string has all its digits equal to one another except this digit which has to be flipped, and this digit must be different than all other digits of the string. The value of this digit could be either zero or one. Hence, this string will either have exactly one digit equal to zero, and all other digits equal to one, or exactly one digit equal to one, and all other digit equal to zero.
Therefore, we only need to check whether the string has exactly one digit equal to zero/one, and if so, the answer is yes; otherwise the answer is no.
`bool` `canMakeAllSame(string str)`
`{`
`    ``int` `zeros = 0, ones = 0;`

`    ``// Traverse through given string and`
`    ``// count numbers of 0's and 1's`
`    ``for` `(``char` `ch : str)`
`       ``(ch == ``'0'``)? ++zeros : ++ones;`

`    ``// Return true if any of the two counts`
`    ``// is 1`
`    ``return` `(zeros == 1 || ones == 1);`
`}`