|
| 1 | +/***************************************** |
| 2 | +1009. Complement of Base 10 Integer |
| 3 | + |
| 4 | +Every non-negative integer N has a binary representation. |
| 5 | +For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. |
| 6 | +Note that except for N = 0, there are no leading zeroes in any binary representation. |
| 7 | +The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. |
| 8 | +For example, the complement of "101" in binary is "010" in binary. |
| 9 | +For a given number N in base-10, return the complement of it's binary representation as a base-10 integer. |
| 10 | + |
| 11 | +Example 1: |
| 12 | +Input: 5 |
| 13 | +Output: 2 |
| 14 | +Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. |
| 15 | + |
| 16 | +Example 2: |
| 17 | +Input: 7 |
| 18 | +Output: 0 |
| 19 | +Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. |
| 20 | + |
| 21 | +Example 3: |
| 22 | +Input: 10 |
| 23 | +Output: 5 |
| 24 | +Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. |
| 25 | + |
| 26 | +Note: |
| 27 | +0 <= N < 10^9 |
| 28 | +****************************************/ |
| 29 | + |
| 30 | + |
| 31 | +class Solution { |
| 32 | + public int bitwiseComplement(int N) { |
| 33 | + String OriBStr = Integer.toBinaryString(N); |
| 34 | + int len = OriBStr.length(); |
| 35 | + |
| 36 | + StringBuilder sb = new StringBuilder(); |
| 37 | + char[] arr = OriBStr.toCharArray(); |
| 38 | + |
| 39 | + for (int i = 0; i < len; i ++) { |
| 40 | + if (arr[i] == '1') {sb.append('0');} |
| 41 | + if (arr[i] == '0') {sb.append('1');} |
| 42 | + } |
| 43 | + |
| 44 | + int NewB = Integer.valueOf(sb.toString(),2); |
| 45 | + |
| 46 | + return NewB; |
| 47 | + } |
| 48 | +} |
0 commit comments