果d題目啱哂先最難,仲要限數
總有d陰濕野例如俾個array你要預埋length係1
佢sample全正數你要預埋有負數
佢sample隻隻數唔同你要預可能隻隻數一樣
甚至result唔好加到多過int max value
好多陰濕野
衰左,果刻最後慌撚左諗唔到點做return
果d題目啱哂先最難,仲要限數
總有d陰濕野例如俾個array你要預埋length係1
佢sample全正數你要預埋有負數
佢sample隻隻數唔同你要預可能隻隻數一樣
甚至result唔好加到多過int max value
好多陰濕野
<pre><code data-type="">public class Solution {
public int[] powerSet;
public int[] solution(int[] A) {
int length = A.length;
if (length == 0)
return A;
powerSet = new int[length];
int sum = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] == 1) {
int power = pow(-2, i);
powerSet[i] = power;
sum += power;
}
}
int ceil;
if (sum % 2 == 1 && sum > 0) {
ceil = sum / 2 + 1;
} else {
ceil = sum / 2;
}
if (ceil == 0) {
return A;
}
int index = getLeadingIndex(ceil);
int[] array = new int[index+1];
array[index] = 1;
ceil -= powerSet[index];
while (ceil != 0) {
index = getLeadingIndex(ceil);
array[index] = 1;
ceil -= powerSet[index];
}
return array;
}
public int pow(int base, int power) {
int number = 1;
while (power-- > 0) {
number *= base;
}
return number;
}
public int getLeadingIndex (int number) {
int index = 0;
int sum = 0;
if (number > 0) {
index = -2;
while (sum < number) {
index += 2;
sum += powerSet[index];
}
} else if (number < 0) {
index = -1;
while (sum > number) {
index += 2;
sum += powerSet[index];
}
}
return index;
}
}</code></pre>
漏咗個checking ceil == 0
int[] array = new int[index+1];
array[index] = 1;