第十四题
- 功能描述:统计一个数字转为二进制后,0和1的个数,组成数组返回
- 输入:6
- 输出:{1,2}
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
int[] result = getNum(6);
System.out.println(Arrays.toString(result));
}
public static int[] getNum(int data) {
String dataStr = Integer.toBinaryString(data);
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < dataStr.length(); i++) {
Integer integer = map.get(dataStr.charAt(i));
map.put(dataStr.charAt(i), integer == null ? 1 : integer + 1);
}
int[] result = new int[2];
result[0] = map.get('0');
result[1] = map.get('1');
return result;
}
}