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;
}
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;
}
}
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;
}
}
上面個題唔使咁做
for每個element
前一個index加1(變咗一半)
之後處理進位(進位係後一個index減1)
print返array就得
佢個數可以好大實overflow