Given two integers L and R, the task is to find the count of numbers in the range [L, R] whose first and last digit in the binary representation are the same.
Examples:
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
Naive Approach: The simplest approach is to iterate over the range L to R and find the binary representation of all the numbers and check for each of them, if the first and the last digit in their binary representation is the same or not.
Time Complexity: O((R-L)log(R-L))
Auxiliary Space: O(1)
Efficient Approach: The given problem can be solved based on the following observations:
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void Count_numbers( int L, int R)
{
int count = (R - L) / 2;
if (R % 2 != 0 || L % 2 != 0)
count += 1;
cout << count << endl;
}
int main()
{
int L = 6, R = 30;
Count_numbers(L, R);
}
|
Java
import java.util.*;
class GFG
{
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);
}
public static void main(String[] args)
{
int L = 6 , R = 30 ;
Count_numbers(L, R);
}
}
|
Python3
def Count_numbers(L, R) :
count = (R - L) / / 2
if (R % 2 ! = 0 or L % 2 ! = 0 ) :
count + = 1
print (count)
L = 6
R = 30
Count_numbers(L, R)
|
C#
using System;
class GFG
{
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);
}
public static void Main(String[] args)
{
int L = 6, R = 30;
Count_numbers(L, R);
}
}
|
Javascript
<script>
function Count_numbers(L , R)
{
var count = (R - L) / 2;
if (R % 2 != 0 || L % 2 != 0)
count += 1;
document.write(count);
}
var L = 6, R = 30;
Count_numbers(L, R);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)