Starting with a positive integer N
, we reorder the digits in any order (including the original order) such that the leading digit is not zero.html
Return true
if and only if we can do this in a way such that the resulting number is a power of 2.git
Example 1:github
Input: 1 Output: true
Example 2:this
Input: 10 Output: false
Example 3:code
Input: 16 Output: true
Example 4:htm
Input: 24 Output: false
Example 5:blog
Input: 46 Output: true
Note:排序
1 <= N <= 10^9
這道題說是給了咱們一個正整數N,讓對各位上的數字進行從新排序,可是要保證最高位上不是0,問可否變爲2的指數。剛開始的時候博主理解錯了,覺得是對N的二進制數的各位進行重排序,但除了2的指數自己,其餘數字怎麼也組不成2的指數啊,由於2的指數的二進制數只有最高位是1,其他都是0。後來才發現,是讓對N的十進制數的各位上的數字進行重排序,好比 N=46,那麼換個位置,變成 64,就是2的指數了。搞清了題意後,就能夠開始解題了,因爲N給定了範圍,在 [1, 1e9] 之間,因此其調換位數能組成的二進制數也是有範圍的,爲 [2^0, 2^30] 之間,這樣的話,一個比較直接的解法就是,現將整數N轉爲字符串,而後對字符串進行排序。而後遍歷全部可能的2的指數,將每一個2的指數也轉爲字符串並排序,這樣只要某個排序後的字符串跟以前由N生成的字符串相等的話,則代表整數N是符合題意的,參見代碼以下:leetcode
解法一:字符串
class Solution { public: bool reorderedPowerOf2(int N) { string str = to_string(N); sort(str.begin(), str.end()); for (int i = 0; i < 31; ++i) { string t = to_string(1 << i); sort(t.begin(), t.end()); if (t == str) return true; } return false; } };
下面這種方法沒有將數字轉爲字符串並排序,而是使用了另外一種比較巧妙的方法來實現相似的功能,是經過對N的每位上的數字都變爲10的倍數,並相加,這樣至關於將N的各位的上的數字都加碼到了10的指數空間,而對於全部的2的指數,進行相同的操做,只要某個加碼後的數字跟以前整數N的處理後的數字相同,則說明N是符合題意的。須要注意的是,爲了防止整型移除,加碼後的數字用長整型來表示便可,參見代碼以下:
解法二:
class Solution { public: bool reorderedPowerOf2(int N) { long sum = helper(N); for (int i = 0; i < 31; i++) { if (helper(1 << i) == sum) return true; } return false; } long helper(int N) { long res = 0; for (; N; N /= 10) res += pow(10, N % 10); return res; } };
討論:對於這種驗證數字的問題,老是有窮舉法出現,參見這個帖子,是能把考官氣死的方法,哈哈~
Github 同步地址:
https://github.com/grandyang/leetcode/issues/869
參考資料:
https://leetcode.com/problems/reordered-power-of-2/
https://leetcode.com/problems/reordered-power-of-2/discuss/159513/C%2B%2B-0ms-beats-100
https://leetcode.com/problems/reordered-power-of-2/discuss/149843/C%2B%2BJavaPython-Straight-Forward