|
| 1 | +package easy; |
| 2 | + |
| 3 | +/** |
| 4 | + * Have the function BinaryReversal(str) take the str parameter being passed, |
| 5 | + * which will be a positive integer, take its binary representation |
| 6 | + * (padded to the nearest N * 8 bits), reverse that string of bits, |
| 7 | + * and then finally return the new reversed string in decimal form. |
| 8 | + * --- |
| 9 | + * For example: if str is "47" then the binary version of this integer is 101111, |
| 10 | + * but we pad it to be 00101111. Your program should reverse this binary string |
| 11 | + * which then becomes: 11110100 and then finally return |
| 12 | + * the decimal version of this string, which is 244. |
| 13 | + */ |
| 14 | +public class BinaryReversal { |
| 15 | + |
| 16 | + /** |
| 17 | + * Left pad the string with zeroes, |
| 18 | + * e.g. padLeft("fade", 8) -> "0000fade" |
| 19 | + * |
| 20 | + * @param str string to be padded |
| 21 | + * @param len new fixed length after applying the padding |
| 22 | + * @return padded string (e.g. 000000xxx) |
| 23 | + */ |
| 24 | + private static String padLeft(String str, int len) { |
| 25 | + return String.format("%" + len + "s", str).replace(" ", "0"); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Binary Reversal function. |
| 30 | + * |
| 31 | + * @param str input string |
| 32 | + * @return the decimal version of this string |
| 33 | + */ |
| 34 | + private static int binaryReversal(String str) { |
| 35 | + String binStr = Integer.toBinaryString(Integer.parseInt(str)); |
| 36 | + int add = binStr.length() % 8 == 0 ? 0 : 1; |
| 37 | + int pad = add + binStr.length() / 8; |
| 38 | + String padStr = padLeft(binStr, pad * 8); |
| 39 | + StringBuilder result = new StringBuilder(); |
| 40 | + for (int i = padStr.length() - 1; i >= 0; i--) { |
| 41 | + result.append(Character.getNumericValue(padStr.charAt(i))); |
| 42 | + } |
| 43 | + return Integer.parseInt(result.toString(), 2); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Entry point. |
| 48 | + * |
| 49 | + * @param args command line arguments |
| 50 | + */ |
| 51 | + public static void main(String[] args) { |
| 52 | + var result1 = binaryReversal("47"); |
| 53 | + System.out.println(result1); |
| 54 | + var result2 = binaryReversal("2"); |
| 55 | + System.out.println(result2); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments