Leetcode.869. 重新排序得到 2 的幂---哈希思想

869. 重新排序得到 2 的幂

给定正整数 N ,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。

如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false。

示例 1:
输入:1
输出:true
示例 2:
输入:10
输出:false
示例 3:
输入:16
输出:true
示例 4:
输入:24
输出:false
示例 5:
输入:46
输出:true
提示:
1 <= N <= 10^9

题解:

我们先将1 <= N <= 10^9范围内的2的幂均求出来,接着对于每一个数我们都计算一下其数字组成,这里我们使用哈希思想使用哈希map进行存储。接着我们拿到N,对其也使用一个哈希map来计算一下其数字组成,接着我们遍历前一个哈希map,分别取出此时对应的2的幂的数字组成与Nmap里的数字组成进行一一比较,一旦出现成功,直接return true;若失败则继续找下一个2的幂进行比对即可。

我们也可以在求出所有2的幂后转成字符串对其进行sort排序,接着在将N也转成字符串对其进行sort排序,然后再一一比对是否相等即可。这种方法就不用去求N2的幂的多种排序后的结果了,因为我们让数字组成一样的数字强行变得一样了。

代码:

class Solution {
    
    
    public boolean reorderedPowerOf2(int n) {
    
    
        if(n==10){
    
    
            return false;  
          //这里n为10,其在下面统计数字组成时不会将n存入map中,因为10%10==0,所以没有存入0,会和1视为一个情况
        }
        int[][] hash = new int[32][10];
        int index = 0;
        for(int i=1;i<(int)1e9+10;i<<=1){
    
    
            int temp = i;
            while(temp>0){
    
    
                hash[index][temp%10]++;
                temp/=10;
            }
            index++;
        }

        int[] map = new int[10];
        int count = 0;
        while(n>0){
    
    
            if(map[n%10]==0){
    
    
                count++;  //count为数字种类
            }
            map[n%10]++;
            n/=10;
        }

        int flag = 0;
        for(int i=0;i<index;i++){
    
    
            for(int j=0;j<10;j++){
    
    
                if(hash[i][j]==map[j]){
    
    
                    if(hash[i][j]!=0 && map[j]!=0)
                        flag++;
                }
                else{
    
    
                    break;
                }
            }

            if(flag==count){
    
    
                return true;
            }    
            flag = 0;
        }

        return false;
    }

   
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/xiangguang_fight/article/details/121042179