使用C++找出在第L个和第R个索引之间只有设置位的数字

使用C++找出在第L个和第R个索引之间只有设置位的数字

在给定的问题中,我们需要找到一个数字的值,该数字在给定的范围L、R之间具有所有的设置位。例如 −

Input: L = 1, R = 5
Output: 62
Explanation: representation of given L and R in binary form is 0..0111110

Input: L = 1, R = 4
Output: 30
Explanation: representation of given L and R in binary form is 0..11110

登录后复制

找到解决方案的方法

在给定的问题中,我们将讨论两种方法,暴力法和高效方法。

暴力法

在这种方法中,我们只需遍历给定的范围,并将给定范围内的所有2的幂相加,这将是我们的答案。

示例

#include
using namespace std;
int main() {
int L = 1, R = 3; // the given range
int ans = 0; // our answer
for(int i = L; i