给定两个整数L和R ,任务是查找在[L,R]范围内其二进制表示形式的第一位和最后一位相同的数字计数。
例子:
Input: L = 1, R = 5
Output: 3
Explanation:
(1)10 = (1)2
(2)10 = (10)2
(3)10 = (11)2
(4)10 = (100)2
(5)10 = (101)2
Therefore, 1, 3, 5 has the same first and last digits in their binary representation.
Input: L = 6, R = 30
Output: 12
天真的方法:最简单的方法是在L到R的范围内进行迭代,找到所有数字的二进制表示形式,并检查每个数字,如果二进制表示形式中的第一位和最后一位数字相同或不同。
时间复杂度: O((RL)log(RL))
辅助空间: O(1)
高效的方法:可以根据以下观察结果解决给定的问题:
- 奇数的二进制表示形式始终以1结尾。
- 每个数字在其二进制表示形式中的起始位均为1 。
- 因此,问题减少到找到给定范围内的奇数计数。
请按照以下步骤解决问题:
- 找到[1,R]范围内的奇数计数并将其存储在变量中,例如X。
- 同样,找到[1,L – 1]范围内的奇数计数。让它成为Y。
- 打印X – Y作为答案。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count numbers in range
// [L, R] having same first and last
// digit in the binary representation
void Count_numbers(int L, int R)
{
int count = (R - L) / 2;
if (R % 2 != 0 || L % 2 != 0)
count += 1;
cout << count << endl;
}
// Drivers code
int main()
{
// Given range [L, R]
int L = 6, R = 30;
// Function Call
Count_numbers(L, R);
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
// Function to count numbers in range
// [L, R] having same first and last
// digit in the binary representation
static void Count_numbers(int L, int R)
{
int count = (R - L) / 2;
if (R % 2 != 0 || L % 2 != 0)
count += 1;
System.out.print(count);
}
// Driver code
public static void main(String[] args)
{
// Given range [L, R]
int L = 6, R = 30;
// Function Call
Count_numbers(L, R);
}
}
// This code is contributed by sanjoy_62
Python3
# Python program for the above approach
# Function to count numbers in range
# [L, R] having same first and last
# digit in the binary representation
def Count_numbers(L, R) :
count = (R - L) // 2
if (R % 2 != 0 or L % 2 != 0) :
count += 1
print(count)
# Drivers code
# Given range [L, R]
L = 6
R = 30
# Function Call
Count_numbers(L, R)
# This code is contributed by code_hunt.
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to count numbers in range
// [L, R] having same first and last
// digit in the binary representation
static void Count_numbers(int L, int R)
{
int count = (R - L) / 2;
if (R % 2 != 0 || L % 2 != 0)
count += 1;
Console.Write(count);
}
// Driver code
public static void Main(String[] args)
{
// Given range [L, R]
int L = 6, R = 30;
// Function Call
Count_numbers(L, R);
}
}
// This code is contributed by 29AjayKumar
输出:
12
时间复杂度: O(1)
辅助空间: O(1)