本文共 1375 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要判断给定的正整数 N 是否可以通过重新排列其数字(包括保持原顺序)来形成一个2的幂的数。2的幂指的是2的整数次方,如1, 2, 4, 8, 16等。
我们可以通过以下步骤来解决这个问题:
具体步骤如下:
import java.util.HashMap;import java.util.Map;public class Solution { public boolean reorderedPowerOf2(int N) { // 统计N的数字频率 Map nCount = countDigits(N); // 预先生成所有可能的2的幂的数字频率 for (int i = 0; i < 32; i++) { int power = (int) Math.pow(2, i); Map powerCount = countDigits(power); if (powerCount.equals(nCount)) { return true; } } return false; } // 统计数字的频率 private static Map countDigits(int num) { Map map = new HashMap<>(); String s = Integer.toString(num); for (char c : s.toCharArray()) { int digit = Character.getNumericValue(c); map.put(digit, map.getOrDefault(digit, 0) + 1); } return map; }} 这种方法通过预先生成2的幂的数字频率,确保了在处理输入时的效率,能够快速判断是否存在符合要求的排列。
转载地址:http://udtuz.baihongyu.com/