Next sparse binary number
PROBLEM :
Given an integer n in the input, find its next sparse binary number.A sparse binary number is a number whose binary representation does not contain any consecutive 1s.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is number 'N'
Output:
Print next Sparse binary number,if the input number is not sparse else print the number itself.
Constraints:
1 = T = 100
1 = n = 100000
Example:
Input
2
3
5
Output
4
5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int Next_sparse_binary_number(int ) ;
int sparse(int ) ;
int main()
{
int t,no ;
cin>>t ;
while(t--)
{
cin>>no ;
cout<<Next_sparse_binary_number(no)<<endl ;
}
return 0;
}
int Next_sparse_binary_number(int no)
{
while(1)
{
if(sparse(no))
return no ;
else
no++ ;
}
}
int sparse(int no)
{
int last,curr ;
last=0,curr=0 ;
while(no)
{
curr=no%2 ;
if(curr==1&&last==1)
return 0 ;
no=no/2 ;
last=curr ;
}
return 1 ;
}
---------------------------------------------------------------------------------
Given an integer n in the input, find its next sparse binary number.A sparse binary number is a number whose binary representation does not contain any consecutive 1s.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is number 'N'
Output:
Print next Sparse binary number,if the input number is not sparse else print the number itself.
Constraints:
1 = T = 100
1 = n = 100000
Example:
Input
2
3
5
Output
4
5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int Next_sparse_binary_number(int ) ;
int sparse(int ) ;
int main()
{
int t,no ;
cin>>t ;
while(t--)
{
cin>>no ;
cout<<Next_sparse_binary_number(no)<<endl ;
}
return 0;
}
int Next_sparse_binary_number(int no)
{
while(1)
{
if(sparse(no))
return no ;
else
no++ ;
}
}
int sparse(int no)
{
int last,curr ;
last=0,curr=0 ;
while(no)
{
curr=no%2 ;
if(curr==1&&last==1)
return 0 ;
no=no/2 ;
last=curr ;
}
return 1 ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment