📌  相关文章
📜  计算给定范围内在二进制表示中具有相同第一位和最后一位数字的数字

📅  最后修改于: 2021-10-26 06:07:49             🧑  作者: Mango

给定两个整数LR ,任务是找到范围[L, R]中二进制表示中第一个和最后一个数字相同的数字的计数。

例子:

朴素的方法:最简单的方法是遍历范围LR并找到所有数字的二进制表示并检查它们中的每一个,如果它们的二进制表示中的第一个和最后一个数字相同或不相同。
时间复杂度: 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)