201. Bitwise AND of Numbers Range (数字范围按位相与)

package LeetCode_201

/**
 * 201. Bitwise AND of Numbers Range (数字范围按位相与)
 * https://leetcode.com/problems/bitwise-and-of-numbers-range/description/
 * https://leetcode.wang/leetcode-201-Bitwise-AND-of-Numbers-Range.html
 *
 * Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
 * */
class Solution {
    fun rangeBitwiseAnd(m: Int, n: Int): Int {
        if (m == Int.MAX_VALUE) {
            return m
        }
        var result = m
        for (i in m + 1..n) {
            result = i and result
            if (result == 0 || i == Int.MAX_VALUE) {
                break
            }
        }
        //print("result:$result")
        return result
    }
}
原文地址:https://www.cnblogs.com/johnnyzhao/p/12624186.html