华为笔试题 之 计算数据最多的类型(有效类型)有多少个数据

一、题目

对一个数据a进行分类,分类方法为:此数据a(四个字节大小)的四个字节相加 % 一个给定的值,如果得到的结果小于一个给定的值c,则此结果即为数据a的类型;如果得到的结果大于或者等于c,则此结果无效即为数据a的类型无效。

比如一个数据a = 0x01010101,b = 3,按照分类方法计算(0x01 + 0x01 + 0x01 + 0x01)% 3 = 1。所以如果 c = 2,则此a的类型是1,如果c = 1,则此a的类型是无效。

现给定c = 5,b = 2,数据 a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}。计算数据最多的类型(有效类型)有多少个数据。

二、代码

package com.huawei.nowcoder;

import java.util.HashMap;
import java.util.Map;

public class MyTest {

    public static void main(String[] args) {

        int[] a = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int c = 5, b = 2;

        Map<String, Integer> countMap = new HashMap<>();
        for (int i = 0; i < a.length; i++) {
            String binaryA = Integer.toBinaryString(a[i]);
            String hexA = String.format("%08d", Integer.valueOf(binaryA));
            String[] splitHexA = split(hexA);

            int intA = 0;
            for (int j = 0; j < splitHexA.length; j++) {
                intA += Integer.parseInt(splitHexA[j], 16);
            }

            int afterNum = intA % b;

            if (afterNum < c) {
                Integer num = countMap.get(String.valueOf(afterNum));
                if (null == num) {
                    num = 1;
                } else {
                    num = num + 1;
                }
                countMap.put(String.valueOf(afterNum), num);
            }
        }

        int maxNum = 0;
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            if (maxNum < entry.getValue()) {
                maxNum = entry.getValue();
            }
        }

        System.out.println(maxNum);
    }

    private static String[] split(String fourByteNum) {

        String[] byteData = new String[4];
        int i = 0;
        while (fourByteNum.length() >= 2) {
            byteData[i] = fourByteNum.substring(0, 2);
            fourByteNum = fourByteNum.substring(2);
            i++;
        }

        return byteData;
    }
}

三、测试

5
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值