C++ LeetCode1780判斷數(shù)字是否可以表示成三的冪的和
LeetCode 1780.判斷一個(gè)數(shù)字是否可以表示成三的冪的和
力扣題目鏈接:leetcode.cn/problems/ch…
給你一個(gè)整數(shù) n ,如果你可以將 n 表示成若干個(gè)不同的三的冪之和,請你返回 true ,否則請返回 false 。
對于一個(gè)整數(shù) y ,如果存在整數(shù) x 滿足 y == 3x ,我們稱這個(gè)整數(shù) y 是三的冪。

方法一:二進(jìn)制枚舉
題目分析

解題思路
那么,我們直接開辟一個(gè)數(shù)組,把所有的小于等于nnn的“3的冪”放入數(shù)組
vector<int> three(1, 1); // 初始值是1個(gè)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;
復(fù)雜度分析

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;
}
};
方法二:進(jìn)制轉(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ù)字是否可以表示成三的冪的和的詳細(xì)內(nèi)容,更多關(guān)于C++ LeetCode判斷數(shù)字三的冪和的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解設(shè)計(jì)模式中的模板方法模式及在C++中的使用
這篇文章主要介紹了設(shè)計(jì)模式中的模板方法模式及在C++中的使用,模板方法將邏輯封裝到一個(gè)類中,并采取組合(委托)的方式解決這個(gè)問題,需要的朋友可以參考下2016-03-03
C++?STL容器詳解之紅黑樹部分模擬實(shí)現(xiàn)
本文主要對紅黑樹進(jìn)行了詳細(xì)介紹,并對其核心功能進(jìn)行了模擬實(shí)現(xiàn)。文中的代碼對我們的學(xué)習(xí)或工作有一定的價(jià)值,感興趣的小伙伴可以了解一下2021-12-12
關(guān)于c++編譯protobuf時(shí)提示LNK2001 無法解析的外部符號(hào)的問題
這篇文章主要介紹了關(guān)于c++編譯protobuf時(shí)提示LNK2001 無法解析的外部符號(hào)的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12

