C++ LeetCode1780判斷數(shù)字是否可以表示成三的冪的和
更新時間:2022年12月16日 12:01:39 作者:LetMeFly
這篇文章主要為大家介紹了C++ LeetCode1780判斷數(shù)字是否可以表示成三的冪的和題解示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
LeetCode 1780.判斷一個數(shù)字是否可以表示成三的冪的和
力扣題目鏈接:leetcode.cn/problems/ch…
給你一個整數(shù) n ,如果你可以將 n 表示成若干個不同的三的冪之和,請你返回 true ,否則請返回 false 。
對于一個整數(shù) y ,如果存在整數(shù) x 滿足 y == 3x ,我們稱這個整數(shù) y 是三的冪。

方法一:二進制枚舉
題目分析

解題思路
那么,我們直接開辟一個數(shù)組,把所有的小于等于nnn的“3的冪”放入數(shù)組
vector<int> three(1, 1); // 初始值是1個1
while (three.back() < n) {
three.push_back(three.back() * 3);
}

int num = three.size(), to = 1 << num;
for (int state = 0; state < to; state++) {
int s = 0;
for (int j = 0; j < num; j++) {
if (state & (1 << j)) {
s += three[j];
}
}
if (s == n)
return true;
}
return false;
復雜度分析

AC代碼
C++
class Solution {
public:
bool checkPowersOfThree(int n) {
vector<int> three(1, 1);
while (three.back() < n) {
three.push_back(three.back() * 3);
}
int num = three.size(), to = 1 << num;
for (int state = 0; state < to; state++) {
int s = 0;
for (int j = 0; j < num; j++) {
if (state & (1 << j)) {
s += three[j];
}
}
if (s == n)
return true;
}
return false;
}
};
方法二:進制轉(zhuǎn)換

AC代碼
C++
class Solution {
public:
bool checkPowersOfThree(int n) {
while (n) {
if (n % 3 == 2)
return false;
n /= 3;
}
return true;
}
};以上就是C++ LeetCode1780判斷數(shù)字是否可以表示成三的冪的和的詳細內(nèi)容,更多關(guān)于C++ LeetCode判斷數(shù)字三的冪和的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
OpenCV使用稀疏光流實現(xiàn)視頻對象跟蹤的方法詳解
這篇文章主要為大家詳細介紹了OpenCV如何使用稀疏光流實現(xiàn)視頻對象跟蹤功能,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以參考一下2023-02-02

