Add binary
public String addBinary(String a, String b) {
StringBuilder res = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
// char -> ASCII value: '0' -> 48, '1' -> 49,
// e.g., subtract '0' from '1' and we have 1
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
carry = sum / 2;
res.insert(0, String.valueOf(sum % 2));
}
if (carry == 1) res.insert(0, '1');
return res.toString();
}
Roman to Int
public int romanToInt(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>() {{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}};
int res = 0;
for (int i = 0; i < s.length(); i++) {
// add guard condition to avoid the StringIndexOutOfBoundsException when grap the next character
if (i < s.length() - 1 && map.get(s.charAt(i)) < map.get(s.charAt(i + 1)))
res -= map.get(s.charAt(i));
else res += map.get(s.charAt(i));
}
return res;
}