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

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

解題思路
那么,我們直接開(kāi)辟一個(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ù)字三的冪和的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- C/C++哈希表優(yōu)化LeetCode題解997找到小鎮(zhèn)的法官
- C/C++實(shí)現(xiàn)獲取系統(tǒng)時(shí)間的示例代碼
- C++ LeetCode1805字符串不同整數(shù)數(shù)目
- C++ LeetCode1775通過(guò)最少操作次數(shù)使數(shù)組和相等
- C++ LeetCode1812判斷國(guó)際象棋棋盤(pán)格子顏色
- C++ LeetCode300最長(zhǎng)遞增子序列
- C++?LeetCode1827題解最少操作使數(shù)組遞增
- C/C++題解LeetCode1295統(tǒng)計(jì)位數(shù)為偶數(shù)的數(shù)字
相關(guān)文章
詳解設(shè)計(jì)模式中的模板方法模式及在C++中的使用
這篇文章主要介紹了設(shè)計(jì)模式中的模板方法模式及在C++中的使用,模板方法將邏輯封裝到一個(gè)類(lèi)中,并采取組合(委托)的方式解決這個(gè)問(wèn)題,需要的朋友可以參考下2016-03-03
C++?STL容器詳解之紅黑樹(shù)部分模擬實(shí)現(xiàn)
本文主要對(duì)紅黑樹(shù)進(jìn)行了詳細(xì)介紹,并對(duì)其核心功能進(jìn)行了模擬實(shí)現(xiàn)。文中的代碼對(duì)我們的學(xué)習(xí)或工作有一定的價(jià)值,感興趣的小伙伴可以了解一下2021-12-12
C 語(yǔ)言基礎(chǔ)教程(我的C之旅開(kāi)始了)[五]
C 語(yǔ)言基礎(chǔ)教程(我的C之旅開(kāi)始了)[五]...2007-02-02
關(guān)于c++編譯protobuf時(shí)提示LNK2001 無(wú)法解析的外部符號(hào)的問(wèn)題
這篇文章主要介紹了關(guān)于c++編譯protobuf時(shí)提示LNK2001 無(wú)法解析的外部符號(hào)的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12

