2011-03-31 53 views
4

同樣沒有打印下一最小和最大數量,打印在他們的二進制表示相同數量的1位的下一個最小和一個最大的數位操作:與給定一個整數的1位

後計算數字中的1的數量。如何確定下一個最小的數字?

+4

那麼,這功課呢? (我只問,因爲這是你問的這種類型的第二個問題) – quasiverse 2011-03-31 10:06:22

+1

不...繼續回答它;;) – garima 2011-03-31 10:13:27

+0

讓我們說,我們有n = 0x11001101,x是次最小。這意味着x大於n && x是所有更大中最小的&& x與x具有相同的1位數。這是我的規則從n更改爲x:將最後的0更改爲1;如果它右邊有1位,則將最接近最後0的那個更改爲0;否則,將第一個0改爲1,將第一個0的最接近的1改爲0.我可以在這裏看到遞歸的方式。但仍不清楚基本規律或理論。 – SecureFish 2011-07-28 22:23:49

回答

6

明年很高,你可以使用Hakmem 175:

項目175(高斯帕):

unsigned nexthi_same_count_ones(unsigned a) { 
    /* works for any word length */ 
unsigned c = (a & -a); 
unsigned r = a+c; 
    return (((r^a) >> 2)/c) | r); 
} 

對於下一:

要使用相同數量的1位獲得下一個更高的數降低我不知道一個快速的算法,所以我會使用經典的方法,如果數字>然後2^0 + 2^1 + ... 2^n然後從您的數字中扣除一個並計算比特數。具有n位的第一個數是一個。

+3

oops ...'nexthi_same_count_ones(0)' – pmg 2011-03-31 10:51:13

+2

請問您能解釋一下這個算法嗎?例如,每個計算的含義是什麼 – SecureFish 2011-07-28 22:02:46

+0

@Dumitrescu:我有一個疑問,大多數情況下(特別是C)如果我們執行和操作一個數字及其當下( - 應用於該數字)。它總是會呈現1.我們可以直接將((r^a)>> 2)除以1.爲什麼我需要計算該操作?這只是我的疑問。對不起,如果我不明白的東西。 – 2013-09-22 15:52:04

6

對於較小

int getNextSmaller(int num) { 
    return ~getNextLarger(~num); 
} 

有時候,事情就是這樣簡單。 :)

http://www.sureinterview.com/shwqst/40004

+2

鏈接已損壞。你是怎麼得到這個的?請添加一個例子 – 2014-08-29 16:06:56

7

Here是一個很好的解釋。 :)

1

請參閱下面的樣本編號156。我也發佈了詳細解釋的來源。

{

x = 156 
10011100 becomes 10100011 
To get the next higher number we need to set the 6th bit from LSB and shift 
the string of 1's (3rd,4th,5th) to LSB positions 1,2 and drop 5th bit 

所以我們得到163 - 10100011,這是旁邊有相同數量的1爲156

00011100 - right most string of 1's in x 
00000011 - right shifted pattern except left most bit ------> [A] 
00010000 - isolated left most bit of right most 1's pattern 
00100000 - shiftleft-ed the isolated bit by one position ------> [B] 
10000000 - left part of x, excluding right most 1's pattern ------> [C] 
10100000 - add B and C (OR operation) ------> [D] 
10100011 - add A and D which is required number 163 

最多}

{

uint_t snoob(uint_t x) 
{ 
    uint_t rightOne; 
    uint_t nextHigherOneBit; 
    uint_t rightOnesPattern; 
    uint_t next = 0; 

    if(x){ 
     // right most set bit 
     rightOne = x & -(signed)x; 
     // reset the pattern and set next higher bit 
     // left part of x will be here 
     nextHigherOneBit = x + rightOne; 
     // nextHigherOneBit is now part [D] of the above explanation. 
     // isolate the pattern 
     rightOnesPattern = x^nextHigherOneBit; 
     // right adjust pattern 
     rightOnesPattern = (rightOnesPattern)/rightOne; 
     // correction factor 
     rightOnesPattern >>= 2; 
     // rightOnesPattern is now part [A] of the above explanation. 
     // integrate new pattern (Add [D] and [A]) 
     next = nextHigherOneBit | rightOnesPattern; 
    } 
    return next; 
} 

}

來源:http://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/