给定两个整数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
Javascript
输出:
12
时间复杂度: O(1)
辅助空间: O(1)