|
| 1 | +/** |
| 2 | + * A type of encoding has only 1 byte encode or 2-byte encode. If the first bit |
| 3 | + * is 0, this byte represents 1 character. If the first bit is 1, it represents |
| 4 | + * 2 characters. Given a string of bits, find out whether the last char is 1 |
| 5 | + * byte encoded or 2-byte encoded. |
| 6 | + * |
| 7 | + * Tags: Recursive |
| 8 | + */ |
| 9 | +class LastByte { |
| 10 | + public static void main(String[] args) { |
| 11 | + LastByte l = new LastByte(); |
| 12 | + String s1 = "0xxxxxxx0xxxxxxx0xxxxxxx0xxxxxxx"; |
| 13 | + String s2 = "0xxxxxxx0xxxxxxx1xxxxxxx0xxxxxxx"; |
| 14 | + String s3 = "0xxxxxxx1xxxxxxx1xxxxxxx0xxxxxxx"; |
| 15 | + System.out.println(l.lastByte(s1)); |
| 16 | + System.out.println(l.lastByte(s2)); |
| 17 | + System.out.println(l.lastByte(s3)); |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Recursive |
| 22 | + * Check backwards |
| 23 | + * If s.charAt(-16) is 0, it must be 1 |
| 24 | + * If it is 1, it can be 1 or 0, according to recurse result |
| 25 | + * Recurse with string without last 8 bit |
| 26 | + * If returns 1, it means 1xxxxxxx is not connected with string before |
| 27 | + * If returns 2, it means 1xxxxxxx is part of a 2-byte, return 1 |
| 28 | + */ |
| 29 | + public int lastByte(String s) { |
| 30 | + if (s == null || s.length() < 16) return 1; |
| 31 | + if (s.charAt(s.length() - 16) == '0') return 1; |
| 32 | + return lastByte(s.substring(0, s.length() - 8)) == 1 ? 2 : 1; |
| 33 | + } |
| 34 | +} |
0 commit comments