SHOW:
|
|
- or go back to the newest paste.
| 1 | import java.util.Scanner; | |
| 2 | ||
| 3 | public class Problem08_CountEqualBits {
| |
| 4 | ||
| 5 | public static void main(String[] args) {
| |
| 6 | Scanner input = new Scanner(System.in); | |
| 7 | int n; | |
| 8 | int bit; | |
| 9 | int nextBit; | |
| 10 | int count = 0; | |
| 11 | int pos; | |
| 12 | int j = 31; | |
| 13 | ||
| 14 | ||
| 15 | System.out.print("n= ");
| |
| 16 | n = input.nextInt(); | |
| 17 | for ( j = 31; j >= 0; j--) { //finds the position (j) of the first bit 1
| |
| 18 | - | pos = (int)Math.pow(2, j); //& n; |
| 18 | + | pos = (int)Math.pow(2, j)& n; |
| 19 | //System.out.println(Integer.toBinaryString(pos)); | |
| 20 | ||
| 21 | if (pos != 0) {
| |
| 22 | break; | |
| 23 | } | |
| 24 | } | |
| 25 | for (int i = 0; i < j; i++) {
| |
| 26 | bit = n & 1; | |
| 27 | n = n >> 1; | |
| 28 | nextBit = n & 1; | |
| 29 | ||
| 30 | if (bit == nextBit) {
| |
| 31 | count++; | |
| 32 | } | |
| 33 | ||
| 34 | } | |
| 35 | System.out.printf("Equal bit pairs are: %d", count);
| |
| 36 | } | |
| 37 | ||
| 38 | } |