869. Reordered Power of 2

Medium
You are given an 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 so that the resulting number is a power of two.
Example 1:
Input: n = 1
Output: true
Example 2:
Input: n = 10
Output: false
Constraints:
  • 1 <= n <= 10^9

解題

func reorderedPowerOf2(n int) bool {
poweroftwo := make(map[string]bool) //儲存所有轉換成字串且sort過後的 power of 2
​
poweroftwo[strconv.Itoa(1)] = true
for i:=1; i<=1000000000; i*=2 {
bytes := []byte(strconv.Itoa(i))
sort.Slice(bytes, func(i, j int) bool {
return bytes[i] < bytes[j]
})
poweroftwo[string(bytes)] = true
}
​
bytes := []byte(strconv.Itoa(n)) //將n轉換成字串後sort,比對是否在map中
sort.Slice(bytes, func(i, j int) bool {
return bytes[i] < bytes[j]
})
​
return poweroftwo[string(bytes)]
}