MCPcopy Create free account
hub / github.com/careercup/ctci / getPrevArith

Method getPrevArith

java/Chapter 5/Question5_3/Question.java:203–229  ·  view source on GitHub ↗
(int n)

Source from the content-addressed store, hash-verified

201 }
202
203 public static int getPrevArith(int n) {
204 int temp = n;
205 int c0 = 0;
206 int c1 = 0;
207 while (((temp & 1) == 1) && (temp != 0)) {
208 c1++;
209 temp >>= 1;
210 }
211
212 /* If temp is 0, then the number is a sequence of 0s followed by a sequence of 1s. This is already
213 * the smallest number with c1 ones. Return -1 for an error.
214 */
215 if (temp == 0) {
216 return -1;
217 }
218
219 while ((temp & 1) == 0 && (temp != 0)) {
220 c0++;
221 temp >>= 1;
222 }
223
224 /* Arithmetic:
225 * 2^c1 = 1 << c1
226 * 2^(c0 - 1) = 1 << (c0 - 1)
227 */
228 return n - (1 << c1) - (1 << (c0 - 1)) + 1;
229 }
230
231 public static void binPrint(int i) {
232 System.out.println(i + ": " + Integer.toBinaryString(i));

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected