算法来找到最显著位算法、显著

2023-09-11 04:00:04 作者:不信命只信双手去苦拼

您好,感谢您抽出宝贵时间来回答我的问题。

Hi and thanks for taking the time to answer my question.

我的一个朋友被要求在接受记者采访时以下问题:给定一个二进制数,找到最显著位。我马上想到了以下解决方案,但我不知道这是否是正确的。

A friend of mine was asked at an interview the following question: "Given a binary number, find the most significant bit". I immediately thought of the following solution but am not sure if it is correct.

也就是说,分割线分成两部分,转换成两部分为十进制。如果左子阵列0十进制那么做二进制搜索在右边的子阵,寻找1。

Namely, divide the string into two parts and convert both parts into decimal. If the left-subarray is 0 in decimal then the do binary search in the right subarray, looking for 1.

这是我的其他问题。是最显著位时,最左边的1的二进制数?你能告诉我一个例子,当一个0是一个例子,说明最显著位。

That is my other question. Is the most significant bit, the left-most 1 in a binary number? Can you show me an example when a 0 is the most significant bit with an example and explanation.

似乎有下文,所以我更新的问题,使之更加precise的答案有点混乱。面试官说:您有收到,直到最显著位表示要停止传输数据的数据网站你会如何去告诉程序停止数据传输

There seems to be a bit of confusion in the answers below so I am updating the question to make it more precise. The interviewer said "you have a website that you receive data from until the most significant bit indicates to stop transmitting data" How would you go about telling the program to stop the data transfer"

推荐答案

您也可以使用位转移。伪code:

You could also use bit shifting. Pseudo-code:

number = gets
bitpos = 0
while number != 0
  bitpos++             # increment the bit position
  number = number >> 1 # shift the whole thing to the right once
end
puts bitpos

如果数是零,BITPOS为零。

if the number is zero, bitpos is zero.