Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 27, 2014 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/27d32c76ed3c4b53af80 to your computer and use it in GitHub Desktop.
Save chrislukkk/27d32c76ed3c4b53af80 to your computer and use it in GitHub Desktop.
Career cup 5.3
package Chapter5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FindNumber {
public static int findNext(int n) {
if (n <= 0)
return -1;
int t = n;
int trailingZeroCount = 0;
int onesCount = 0;
// find first trailing 1 if any
while (t > 0 && (t & 1) == 0) {
t = t >> 1;
trailingZeroCount++;
}
// find right most non-trailing 0
while (t > 0 && (t & 1) == 1) {
t = t >> 1;
onesCount++;
}
int pos = trailingZeroCount + onesCount;
if (pos == 31 || pos == 0)
return -1;
// flip right most non-trailing 0 to 1
n = n | (1 << pos);
// set bits left to pos be 0
n = n & (~((1 << pos) - 1));
// set the right most (oneCount - 1) bits to 1
n = n | ((1 << (onesCount - 1)) - 1);
return n;
}
public static int findPrev(int n) {
if (n <= 0)
return -1;
int t = n;
int trailingOneCount = 0;
int zeroCount = 0;
// find first trailing 0 if any
while (t > 0 && ((t & 1) == 1)) {
t = t >> 1;
trailingOneCount++;
}
if (t==0)
return -1;
// find the right most no trailing 1
while (t > 0 && ((t & 1) == 0)) {
t = t >> 1;
zeroCount++;
}
int pos = trailingOneCount + zeroCount;
// flip the pos from 1 to 0;
n = n & (~(1 << pos));
// set all bits right to pos to 0
n = n & (~((1 << pos) - 1));
// set 1s right to the pos
int resetOnes = (1 << (trailingOneCount + 1)) - 1;
n = n | (resetOnes << (zeroCount - 1));
return n;
}
public static void main(String[] args) {
System.out.print("please input a Integer: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = -1;
try {
num = Integer.parseInt(br.readLine());
} catch (IOException ex) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Prev number is " + findPrev(num));
System.out.println("Next number is " + findNext(num));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment