studycoding
BAN USER- 3 Answers a given array and a given value, in the array find the biggest value which is smaller than the given number while has same 1s as the given value
Below is my answer, do you have better solutions?//a given array and a given value, in the array find the biggest value which is smaller than the given number while has same 1s as the given value
- studycoding August 11, 2013
//count 1s in a value.
#include <iostream>
int CountOnes( int value){
int count= 0;
while(value>0){
if((value&0x01) ==1)
count++;
value = value>>1;
}
return count;
}
int SearchValue(int *src, int array_size, int given_num){
int given_ones = CountOnes(given_num);
int des=-1;
for(int i=0; i<array_size; i++){
if(CountOnes(src[i])==given_ones && src[i]<=given_num){
if(des==-1){
des=src[i];
}else{
if(src[i]>des)
des=src[i];
}
}
}
return des;
}
int main(){
int array[]={1, 2, 3, 4, 5, 6, 7, 8 ,10 };
int num = 9;
std::cout<<"the number is "<<SearchValue(array, 10, num);
}| Flag | PURGE