一、题目
对一个数据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