zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    
  • 相关阅读:
    蘑菇街teamtalk简介
    greenDAO简介
    Android 编译错误
    Android 中内容提供者的使用
    Android中使用http协议访问网络
    在Windows环境下设置terminal下调试adb
    Android中SQLite的使用
    sharedPreferences存储数据
    android中广播的使用
    fragment的使用
  • 原文地址:https://www.cnblogs.com/mapoos/p/14563232.html
Copyright © 2011-2022 走看看