2017-03-16 43 views
-1

問題是要找到一個數字中最大的二進制差距,雖然這在我的IDE中工作,但Codility不接受它。有什麼想法嗎?這個Codility Answer有什麼問題?

const biGap = (number) => { 
 
    const binary = number.toString(2) 
 
    const re = /1(0+)1/g; 
 
    const found = binary.match(re) 
 
    let counter = 0 
 
    found.map((match) => { 
 
    if (match.length > counter) { 
 
     counter = match.length 
 
    } 
 
    }) 
 
    return (counter - 2); 
 
} 
 

 
console.log(biGap(1041));

+0

您可以定義 「二元差距」?它只適用於這裏的'1'嗎? –

+0

它看起來不正確。正則表達式找不到重疊匹配,所以如果輸入是「10010000010001」,它將返回包含最長間隔的「1001」和「10001」,但不是「1000001」。 – Barmar

+0

@HunterMcMillen基於他的代碼,它似乎是一個數字的二進制表示中的1位之間的一系列0位。 – Barmar

回答

1

與您的代碼的主要問題是,binary.match(re)不會返回重疊的匹配。因此,如果binary = "1010000001001",它將返回["101", "1001"],這是缺少它們之間的長距離10000001

您可以通過更改正則表達式解決這

const re = /0+1/g; 

那麼你應該返回counter - 1而不是counter - 2

你並不需要把10+因爲number.toString(2)永遠不會包括前導零的兩側,所以總有一個1到零的任何字符串的左邊,這是沒有必要明確匹配。

如果你也想在數字的低位二進制差距,您可以更改正則表達式簡單:

const re = /0+/g; 

然後你返回時,不需要從counter加減。

const biGap = (number) => { 
 
    const binary = number.toString(2) 
 
    const re = /0+1/g; 
 
    const found = binary.match(re) 
 
    let counter = 0 
 
    found.map((match) => { 
 
    if (match.length > counter) { 
 
     counter = match.length 
 
    } 
 
    }) 
 
    return (counter - 1); 
 
} 
 

 
console.log(biGap(1041)); 
 
console.log(biGap(parseInt("1010000001001", 2))); // Your code returns 2