• 0869. Reordered Power of 2 (M)


    Reordered Power of 2 (M)

    题目

    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

    题意

    将一个整数x的各位数字重新组合后得到一个新数y(不以0开头),判断是否存在一个正好是2的幂的y。

    思路

    定义一个整数的规范形式为将其各位数排序后组成的字符串,那么只要两个整数的规范形式相同,我们就可以认为这两个整数是等价的。注意到已经限制了输入的N的范围,只需要将该范围内所有2的幂的规范形式存入HashSet,每次判断都将整数转化为规范形式再查找是否在HashSet中出现。


    代码实现

    Java

    class Solution {
        private Set<String> set = new HashSet<>();
    
        public Solution() {
            int i = 1;
            while (i <= 1000000000) {
                set.add(normalize(i));
                i *= 2;
            }
        }
    
        public boolean reorderedPowerOf2(int N) {
            return set.contains(normalize(N));
        }
    
        private String normalize(int N) {
            String[] arr = String.valueOf(N).split("");
            Arrays.sort(arr);
            return String.join("", arr);
        }
    }
    
  • 相关阅读:
    Linux 分区与挂载
    Linux Shell 编程总结
    Java AtomicIntegerFieldUpdater 抽象类
    Java 内部类加载顺序
    Java AtomicIntegerArray 类
    Java AtomicInteger 类
    Java ReentrantLock 类
    Java Runnable 接口
    Java Supplier 接口
    Java Consumer 接口
  • 原文地址:https://www.cnblogs.com/mapoos/p/14563232.html
Copyright © 2020-2023  润新知