当前位置:网站首页>Tencent interview: can you find the number of 1 in binary?
Tencent interview: can you find the number of 1 in binary?
2022-07-03 23:25:00 【Tao song remains the same】
Hello everyone , I'm brother Tao .
today , Let's look at a Tencent interview question : It is known that n Is a non negative integer , In the binary system 1 The number of , The efficiency of the algorithm is required to be as high as possible .
What exactly does this topic mean ? We assume that n = 20, Then its binary is :10100, So binary is 1 The number of is 2 individual .
The problem seems extremely simple , But finding efficient algorithms is not easy . Next , Let's look at the specific solution step by step , And do extended exercises .
Night view of Tencent Binhai building
Routine solution
We can find out directly n The binary value of , Then count the value as 1 Bit , In this way, the functions in the topic can be realized , The procedure is as follows :
#include<iostream>
using namespace std;
int getNumber1(int n)
{
int r = 2, sum = 0;
while(n)
{
if(1 == n % r)
sum++;
n /= r;
}
return sum;
}
int main()
{
cout << getNumber1(20) << endl; // The result is 2
return 0;
}
The result is 2, The answer right . however , This is to traverse every bit of binary , The efficiency is not high , Unable to pass the interview of Tencent .
Shift solution
Each bit of binary can be associated with 1 Operation and operation , It also traverses binary values one by one , The answer right , But I can't pass the Tencent interview .
#include<iostream>
using namespace std;
int getNumber2(int n)
{
int sum = 0;
while(n)
{
if(1 == (n & 1))
sum++;
n >>= 1;
}
return sum;
}
int main()
{
cout << getNumber2(20) << endl; // The result is 2
return 0;
}
The recursive method
If not necessary , Please don't use recursive algorithm in the interview , This is especially true in practical work . The following answer is correct , But I can't pass the Tencent interview .
#include<iostream>
using namespace std;
int getNumber3(int n)
{
if(0 == n)
{
return 0;
}
return getNumber3(n & (n - 1)) + 1;
}
int main()
{
cout << getNumber3(20) << endl; // The result is 2
return 0;
}
in addition , Some friends may question , Why is the recursive relation like this ? Don't worry , Keep looking down and you will understand .
The optimal solution
We set up n = 20, You can work out n - 1 Value , Please pay attention to n The last bit of binary 1 And behind it 0, This string of numbers must be 100... In the form of , that n - 1 The value of must be 00...1 In the form of .
When executed n & (n - 1) when , Obviously, you can see , The result is the elimination of n The last one in the class 1 Value , The rest of the bits remain unchanged , This is a very important feature . Look at the picture below , You'll see :
( explain , There's something wrong with this picture ,n-1 Should be 10011, But it doesn't affect the results )
remember f(n) by n Binary is 1 The number of , It's easy to get :f(n) = f(n & (n - 1)) + 1, therefore , The corresponding procedure is as follows :
#include<iostream>
using namespace std;
int bestSolution(int n)
{
int sum = 0;
while(n)
{
sum++;
n = n & (n - 1);
}
return sum;
}
int main()
{
cout << bestSolution(20) << endl; // The result is 2
return 0;
}
The result is 2, Absolutely right , And avoid bit by bit operation , It's a very efficient algorithm , You can pass the interview of Tencent .
Extended exercises
Next , Let's look at the extended exercises , Please judge whether a positive integer is 2 Omega to an integer power , Let's take a direct look at the following procedure :
#include<iostream>
using namespace std;
bool bestSolution(int n)
{
if (n == 0)
{
return false;
}
if ((n & (n - 1)) == 0) // Indicates that there is only one... In the binary 1
{
return true;
}
return false;
}
int main()
{
for(int n = 0; n < 100; n++)
{
if (bestSolution(n))
{
cout << n << endl;
}
}
return 0;
}
The result is :
1
2
4
8
16
32
64
well ,bestSolution The solution is very clever , Must understand and master . Some friends may want to say : Who wants this method at the scene ?
you 're right , Only when you are well prepared can you think of , The questions to brush , Still brush , Otherwise, the interview site is basically confused . I wish you all a smooth journey through the written examination and interview .
边栏推荐
- ADB related commands
- The first game of the new year, many bug awards submitted
- Fudan 961 review
- SQL data update
- Hcip day 14 notes
- Apple released a supplementary update to MacOS Catalina 10.15.5, which mainly fixes security vulnerabilities
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- Firefox set up proxy server
- Creation of the template of the password management software keepassdx
- Blue Bridge Cup -- guess age
猜你喜欢
SDMU OJ#P19. Stock trading
Esp-idf turns off serial port log output.
Qtoolbutton available signal
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
Actual combat | use composite material 3 in application
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
Weekly leetcode - nc9/nc56/nc89/nc126/nc69/nc120
Blue Bridge Cup -- guess age
Format cluster and start cluster
Current detection circuit - including op amp current scheme
随机推荐
Overview of Yunxi database executor
Deep learning ----- using NN, CNN, RNN neural network to realize MNIST data set processing
Gossip about redis source code 75
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Hcip day 16 notes
Yyds dry goods inventory [practical] simply encapsulate JS cycle with FP idea~
股票开户最低佣金炒股开户免费,网上开户安全吗
FPGA tutorial and Allegro tutorial - link
Powerful blog summary
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
2022 free examination questions for hoisting machinery command and hoisting machinery command theory examination
SDMU OJ#P19. Stock trading
Esp-idf turns off serial port log output.
Hcip 13th day notes
[15th issue] Tencent PCG background development internship I, II and III (OC)
Minimum commission for stock account opening. Stock account opening is free. Is online account opening safe
D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
Shell script three swordsman awk
Learning methods of zynq