[Leetcode 201, medium] Bitwise AND of Numbers Range
来源:互联网 发布:win10需要优化软件吗 编辑:程序博客网 时间:2024/06/05 21:52
Problem:
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
Analysis:
Solutions:
C++:
int rangeBitwiseAnd(int m, int n) { if(m == n) return m; unsigned int m_temp = m; unsigned int num_digits = 0; while(m_temp != 0) { ++num_digits; m_temp /= 2; } unsigned int new_number = 1; for(int i = 0; i < num_digits; ++i) new_number *= 2; if(new_number <= n) return 0; unsigned int result = m; for(unsigned int index = m + 1; index <= n; ++index) result &= index; return int(result); }Java:
Python:
0 0
- 关于SNMP的MIB文件的语法简述
- snmp开发
- Python通过thrift访问hadoop:报错java.lang.IllegalArgumentException: Wrong FS: hdfs:/ expected file:///
- 让GIT DIFF/MERGE使用MELD等GUI对比工具
- iOS面试题收集(一)
- [Leetcode 201, medium] Bitwise AND of Numbers Range
- iOS面试题收集(二)
- iOS面试题收集(三)
- iOS面试题收集(四)
- 美工如何提供按钮图片给开发者
- html学习 - canvas拉伸问题
- iOS面试题收集(五)
- 两个星期的假,可以好好休息一下。
- [Leetcode 130, medium] Surrounded regions