题目

类型:Array
image.png

解题思路

举例入参为46

  • 经过代码中的init方法,首先会把1到10的9次方所有偶数(也就是2的幂)都通过countDigits方法计算一遍
  • countDigits所做的工作就是初始化10位数的char数组,把4和6上的位置1,然后转成string存到HashSet里面
  • 然后所有数字都初始化之后再判断入参经过countDigits方法后是否存在于Set中

image.png

代码

  1. class Solution {
  2. Set<String> powerOf2Digits = new HashSet<String>();
  3. public boolean reorderedPowerOf2(int n) {
  4. init();
  5. return powerOf2Digits.contains(countDigits(n));
  6. }
  7. public void init() {
  8. for (int n = 1; n <= 1e9; n <<= 1) {
  9. powerOf2Digits.add(countDigits(n));
  10. }
  11. }
  12. public String countDigits(int n) {
  13. char[] cnt = new char[10];
  14. while (n > 0) {
  15. ++cnt[n % 10];
  16. n /= 10;
  17. }
  18. return new String(cnt);
  19. }
  20. }