[LeetCode] 869. Reordered Power of 2 重新排序為2的倍數



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.

Return true if and only if we can do this in a way such that the resulting number is a power of 2.

Example 1:

Input: 1
Output: true

Example 2:

Input: 10
Output: false

Example 3:

Input: 16
Output: true

Example 4:

Input: 24
Output: false

Example 5:

Input: 46
Output: true

Note:

  1. 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是符合題意的,參見代碼如下:
解法一:
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;
    }
};

討論:對於這種驗證數字的問題,總是有窮舉法出現,參見[這個帖子](https://leetcode.com/problems/reordered-power-of-2/discuss/159513/C%2B%2B-0ms-beats-100),是能把考官氣死的方法,哈哈~
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

https://leetcode.com/problems/reordered-power-of-2/discuss/151949/Simple-Java-Solution-Based-on-String-Sorting


[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM