今天好友微软笔试,把题目发给我看了,不过由于英语不好,看了很久才懂,唉,题目如下:
Here goes the question:
>
> Write a method that find the int that has the most occurred number 1 in the input int array, and write test cases that you can think.
>
> Please return me the answer no later than 20:20.
这上面的1当时理解为整形的二进制中的1,则代码如下:
#include<iostream>
using namespace std;
int onenum (unsigned int iDec)
{
int size = 0;
unsigned int temp;
int i=31;
while(i>=0)
{
temp=iDec;
temp=temp>>i;
temp=temp&1;
if (1 == temp)
{
size++;
}
i--;
}
return size;
}
int main()
{
unsigned int a=3;
int arr[] = {1,117,2,3};
int len = sizeof(arr)/sizeof(int);
int cnt[10];
int max=0,flag;
for (int i=0;i<len;i++)
{
cnt[i] = onenum(arr[i]);
if(max<cnt[i])
{
max = cnt[i];
flag = i;
}
}
cout<<"The max is "<<flag<<endl;
return 1;
}
第二次看的时候,有可能觉得出题者的意思是说整形数中1的个数,所以为此将代码改了下:
#include<iostream>
using namespace std;
int onenum (unsigned int iDec)
{
int num = 0;
while(iDec/10)
{
if(1 == iDec%10)
{
num++;
}
iDec = iDec/10;
}
if(1 == iDec%10)
{
num++;
}
return num;
}
int main()
{
unsigned int a=3;
int arr[] = {1,117,2,3};
int len = sizeof(arr)/sizeof(int);
int cnt[10];
int max=0,flag;
for (int i=0;i<len;i++)
{
cnt[i] = onenum(arr[i]);
if(max<cnt[i])
{
max = cnt[i];
flag = i;
}
}
cout<<"The max is "<<flag<<endl;
return 1;
}