C++ LeetCode1780判斷數(shù)字是否可以表示成三的冪的和
LeetCode 1780.判斷一個數(shù)字是否可以表示成三的冪的和
力扣題目鏈接:leetcode.cn/problems/ch…
給你一個整數(shù) n
,如果你可以將 n
表示成若干個不同的三的冪之和,請你返回 true
,否則請返回 false
。
對于一個整數(shù) y
,如果存在整數(shù) x
滿足 y == 3x
,我們稱這個整數(shù) y
是三的冪。
方法一:二進(jìn)制枚舉
題目分析
解題思路
那么,我們直接開辟一個數(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;
復(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)文章
OpenCV使用稀疏光流實(shí)現(xiàn)視頻對象跟蹤的方法詳解
這篇文章主要為大家詳細(xì)介紹了OpenCV如何使用稀疏光流實(shí)現(xiàn)視頻對象跟蹤功能,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,需要的可以參考一下2023-02-02C++ Boost Container庫示例詳細(xì)講解
Boost是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱。Boost庫是一個可移植、提供源代碼的C++庫,作為標(biāo)準(zhǔn)庫的后備,是C++標(biāo)準(zhǔn)化進(jìn)程的開發(fā)引擎之一,是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱2022-11-11Qt+OpenCV實(shí)現(xiàn)目標(biāo)檢測詳解
這篇文章主要介紹了如何利用Qt和OpenCV中自帶xml文件實(shí)現(xiàn)目標(biāo)檢測,文中的實(shí)現(xiàn)過程講解詳細(xì),感興趣的小伙伴可以動手試一試2022-03-03