How to count the number of set bits in ASCII string
Posted onViews: Disqus:
这是最近看到的一个算法题,第一眼看过去连题目都看不懂啊囧。非计算机本科生表示对算法十分无力。第一直觉肯定是把ASCII的字符都换成int,然后题目就可以变成How to count the number of set bits in integer. google一下还真有[答案](How to count the number of set bits in ASCII string).第一个高分回答表示各种位操作都看不懂。传说中的Hamming_weight算法。真是给跪了。
publicstatic String asc2bin(String str){ StringBuilder binaryString = new StringBuilder(8 * str.length()); for (int i = 0; i < str.length(); i++) { try { int ascInt = (int) str.charAt(i); StringBuilder temp = new StringBuilder(Integer.toBinaryString(ascInt)); String bin = null; if (temp.length() <= DEFAULT_LENGTH) { while (temp.length() < DEFAULT_LENGTH) { temp.insert(0, "0"); } bin = temp.toString(); } elseif (temp.length() > DEFAULT_LENGTH) { continue; } binaryString.append(bin); } catch (NumberFormatException nfe) { continue; } } return binaryString.toString(); }
publicstatic String bin2asc(String str){ StringBuilder sb = new StringBuilder();
//10010001100101 split into 8 characters for (int i = 0; i < str.length() - 1; i += DEFAULT_LENGTH) {
//grab the hex in pairs String output = str.substring(i, (i + DEFAULT_LENGTH)); //convert hex to decimal int decimal = Integer.parseInt(output, 2); //convert the decimal to character sb.append((char) decimal); }