您好,欢迎访问一九零五行业门户网

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

在给定的问题中,我们需要找到一个数字的值,该数字在给定的范围l、r之间具有所有的设置位。例如 −
input: l = 1, r = 5output: 62explanation: representation of given l and r in binary form is 0..0111110input: l = 1, r = 4output: 30explanation: representation of given l and r in binary form is 0..11110
找到解决方案的方法在给定的问题中,我们将讨论两种方法,暴力法和高效方法。
暴力法在这种方法中,我们只需遍历给定的范围,并将给定范围内的所有2的幂相加,这将是我们的答案。
示例#include<bits/stdc++.h>using namespace std;int main() { int l = 1, r = 3; // the given range int ans = 0; // our answer for(int i = l; i <= r; i++) // traversing through the whole range ans += pow(2, i); // adding values to the answer. cout << ans << "\n";}

输出14

在这种方法中,我们只是遍历范围并简单地将范围内的数字的2的幂相加。这个程序的时间复杂度为o(n),其中n是我们范围的大小。但是我们可以通过应用给定问题中的位知识进一步改进时间复杂度。
高效的方法在这种方法中,我们将简单地构造一个公式来计算我们的答案。
示例#include<bits/stdc++.h>using namespace std;int main() { int l = 1, r = 3; // the given range int ans = 0; // our answer for(int i = l; i <= r; i++) // traversing through the whole range ans += pow(2, i); // adding values to the answer. cout << ans << "\n";}

输出14

在这种方法中,我们制定了一个计算答案的公式。
上述代码的解释正如您所知,我们需要计算给定范围内具有设置位的数字,因此在这种方法中,我们找到一个从0到r的所有位都设置的数字。然后我们需要从1到(l-1)中减去一个所有位都设置的数字,因此我们制定了这个观察结果。给定代码的总体时间复杂度为o(1),即常数时间复杂度,这意味着我们可以在常数时间内计算任何答案。
结论本文将为“仅在l-th和r-th索引之间具有设置位的数字”编写一个程序。我们还学习了解决此问题的c++程序和完整的方法(普通和高效)。我们可以使用其他语言(如c、java、python和其他语言)编写相同的程序。希望您会发现本文有帮助。
以上就是使用c++找出在第l个和第r个索引之间只有设置位的数字的详细内容。
其它类似信息

推荐信息