| 116 | } |
| 117 | |
| 118 | public static int getNextArith(int n) { |
| 119 | int c = n; |
| 120 | int c0 = 0; |
| 121 | int c1 = 0; |
| 122 | while (((c & 1) == 0) && (c != 0)) { |
| 123 | c0++; |
| 124 | c >>= 1; |
| 125 | } |
| 126 | |
| 127 | while ((c & 1) == 1) { |
| 128 | c1++; |
| 129 | c >>= 1; |
| 130 | } |
| 131 | |
| 132 | /* If c is 0, then n is a sequence of 1s followed by a sequence of 0s. This is already the biggest |
| 133 | * number with c1 ones. Return error. |
| 134 | */ |
| 135 | if (c0 + c1 == 31 || c0 + c1 == 0) { |
| 136 | return -1; |
| 137 | } |
| 138 | |
| 139 | /* Arithmetically: |
| 140 | * 2^c0 = 1 << c0 |
| 141 | * 2^(c1-1) = 1 << (c0 - 1) |
| 142 | * next = n + 2^c0 + 2^(c1-1) - 1; |
| 143 | */ |
| 144 | |
| 145 | return n + (1 << c0) + (1 << (c1 - 1)) - 1; |
| 146 | } |
| 147 | |
| 148 | public static int getPrev(int n) { |
| 149 | int temp = n; |