|
1 |
| -package me.ramswaroop.bitmanipulation; |
| 1 | +package com.hackerrank.bitmanipulation; |
2 | 2 |
|
3 | 3 | import java.io.BufferedReader;
|
4 | 4 | import java.io.IOException;
|
|
14 | 14 | public class Solution {
|
15 | 15 | private final static byte BITS;
|
16 | 16 | private final static long[] BIT_COUNT_TO_BIT;
|
| 17 | + |
17 | 18 | static {
|
18 | 19 | BITS = 32;
|
19 |
| - BIT_COUNT_TO_BIT = new long[BITS+1]; |
| 20 | + BIT_COUNT_TO_BIT = new long[BITS + 1]; |
20 | 21 | BIT_COUNT_TO_BIT[0] = 1;
|
21 |
| - for(byte i = 1; i <= BITS; i++){ |
22 |
| - BIT_COUNT_TO_BIT[i] = ((BIT_COUNT_TO_BIT[i-1] - 1L) << 1) + (1L << (i-1)) + 1L; |
| 22 | + for (byte i = 1; i <= BITS; i++) { |
| 23 | + BIT_COUNT_TO_BIT[i] = ((BIT_COUNT_TO_BIT[i - 1] - 1L) << 1) + (1L << (i - 1)) + 1L; |
23 | 24 | }
|
24 | 25 | }
|
| 26 | + |
25 | 27 | public static void main(String[] args) throws IOException {
|
26 | 28 | StringBuffer sb = new StringBuffer();
|
27 | 29 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
28 |
| - for(short T = Short.parseShort(br.readLine()); T > 0; T--){ |
| 30 | + for (short T = Short.parseShort(br.readLine()); T > 0; T--) { |
29 | 31 | String[] temp = br.readLine().split(" ");
|
30 | 32 | int A = Integer.parseInt(temp[0]);
|
31 | 33 | int B = Integer.parseInt(temp[1]);
|
32 | 34 | long bits = bitCountToNum(B) - bitCountToNum(A) + getHammingWeight(A);
|
33 |
| - bits += (A < 0 && B >= 0) ? BIT_COUNT_TO_BIT[BITS] - 1L: 0; |
| 35 | + bits += (A < 0 && B >= 0) ? BIT_COUNT_TO_BIT[BITS] - 1L : 0; |
34 | 36 | sb.append(bits + "\n");
|
35 | 37 | }
|
36 | 38 | System.out.print(sb);
|
37 | 39 | }
|
| 40 | + |
38 | 41 | //Bit count in number
|
39 |
| - private static int getHammingWeight(int n){ |
| 42 | + private static int getHammingWeight(int n) { |
40 | 43 | byte count = 0;
|
41 |
| - while(n != 0){ |
| 44 | + while (n != 0) { |
42 | 45 | count++;
|
43 |
| - n &= n-1; |
| 46 | + n &= n - 1; |
44 | 47 | }
|
45 | 48 | return count;
|
46 | 49 | }
|
| 50 | + |
47 | 51 | //Bit count to number, inclusive
|
48 |
| - private static long bitCountToNum(int n){ |
| 52 | + private static long bitCountToNum(int n) { |
49 | 53 | long count = 0;
|
50 |
| - for(byte b = BITS; n != 0;){ |
| 54 | + for (byte b = BITS; n != 0; ) { |
51 | 55 | int x = 1 << --b;
|
52 |
| - if((n & x) != 0){ |
| 56 | + if ((n & x) != 0) { |
53 | 57 | n &= ~x;
|
54 | 58 | count += BIT_COUNT_TO_BIT[b] + n;
|
55 | 59 | }
|
|
0 commit comments