You are viewing a single comment's thread. Return to all comments →
class Result { public static long flippingBits(long n) { bool[] bits = convertToBits(n); for (int i = 0; i < bits.Length; i++) bits[i] = !bits[i]; return convertToLong(bits); } public static bool[] convertToBits(long l) { bool[] result = new bool[32]; for (int i = 0; i < result.Length; i++) { int pow = (result.Length - 1) - i; if (l / powOf2(pow) > 0) { result[i] = true; l -= powOf2(pow); } } return result; } public static long convertToLong(bool[] bits) { long result = 0; for (int i = 0; i < bits.Length; i++) { int index = (bits.Length - 1) - i; if (bits[index]) result += powOf2(i); } return result; } public static long powOf2(int n) { long result = 1; for (int i = 0; i < n; i++) result *= 2; return result; } }
Seems like cookies are disabled on this browser, please enable them to open this website
Flipping bits
You are viewing a single comment's thread. Return to all comments →