給定一個正整數 A,回傳一個最小長度的陣列,其元素是 3 的冪,并且所有元素的總和等于 A。
對于輸入 A = 13:
- 3 0 = 1, 3 1 = 3, 3 2 = 9。
- 1 3 9 = 13。
所以 A = 13 可以表示為 1、3 和 9 的總和。
有沒有更好的方法來解決這個問題?
public static int[] getSolve(int A) {
List<Integer> binary = new ArrayList<>();
while (A > 0) {
int r = A % 3;
binary.add(r);
A /= 3;
}
// System.out.println(binary.toString());
List<Integer> res = new ArrayList<>();
int j = 0;
for (int i = 0; i < binary.size(); i ) {
if (binary.get(i) != 0) {
while (j < binary.get(i)) {
res.add((int) Math.pow(3, i));
j ;
}
j =0;
}
}
return res.stream().mapToInt(i -> i).toArray();
}
uj5u.com熱心網友回復:
這個問題的答案總是以 3 為底的表示,也稱為三元。
我最大的建議是不需要你的binary資料結構。當您找到余數時,就在那里,然后您可以查看余數是否存在,并將適當的 3 次冪添加到您的答案中。
uj5u.com熱心網友回復:
對于 python 的人來說,它可能很有用
class Solution: # @param A : integer # @return 一個整數串列 def solve(self, A): bits = [] solution = []
while(A != 0):
bits.append(A % 3);
A = A // 3;
for i in range(len(bits)):
if(bits[i] != 0):
tmp = 0;
while(tmp < bits[i]):
solution.append(pow(3, i));
tmp = tmp 1
return solution
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/350507.html
上一篇:在lua中反轉指數
