Cho số nguyên dương N, sắp xếp lại chữ số (không cho 0 dẫn đầu) sao cho thành lũy thừa của 2. Kiểm tra có thể không.
Ví dụ: 46 → true (64 = 2⁶).
Giải pháp:
Hàm count(x): tính "dấu vân tay" chữ số: sum 10^(chữ số)
x = count(N)
For i=0..31: nếu count(2^i) == x → true
Trả về false
Vì 2³¹ > 10⁹, chỉ cần kiểm tra 32 lũy thừa đầu tiên.
Ví dụ
#include <bits/stdc++.h> using namespace std; class Solution { public: int count(int x){ int ret=0; while(x){ ret += pow(10, x%10); x/=10; } return ret; } bool reorderedPowerOf2(int N) { int x = count(N); for(int i=0;i<32;i++) if(count(1<<i)==x) return true; return false; } }; int main(){ Solution ob; cout << ob.reorderedPowerOf2(812); }Đầu vào
812
Đầu ra
1