/** * This problem was asked by Yahoo. * Write a function that returns the bitwise AND of all integers between M and N, inclusive. * */ class Problem_691 { /* * solution: Most Significant Bit (msb), 最高有效位, 在大端序中,msb就是左最边的位 * 1. get msb of two number * 2. if two msb are equals, return 0; else add 2^msp_value into result * 3. subtract msp_value from m and n * */ fun bitwiseAND(m_: Int, n_: Int): Int { var m = m_ var n = n_ var result = 0 while (m > 0 && n > 0) { val msbM = msbPosition(m) val msbN = msbPosition(n) if (msbM != msbN) { break } val msbValue = 1 shl msbM//1 shl msbM = 2^msbM = 2的msbM次方 result += msbValue m -= msbValue n -= msbValue } return result } private fun msbPosition(n_: Int): Int { var msb = -1 var n = n_ //position++ when n shift right until n==0 (mean reach n's most highest bit) while (n > 0) { n = n shr 1 msb++ } return msb } }