import java.math.BigInteger; public class InterestingSet { public static void main(String[] args) { int n = 9; int k = 2; long rs = new InterestingSet().kthInterestingNumber(n, k); System.out.println(rs); } private long kthInterestingNumber(int n, int k) { char[] strNumber = Long.toBinaryString(n).toCharArray(); for (int i = 0; i < k; i++) { strNumber = biggerThanIt(strNumber); } return parseBinaryLong(new String(strNumber)); } private char[] biggerThanIt(char[] charNumbers) { int firstZero = charNumbers.length - 1; int firstOne = charNumbers.length - 1; for (int i = charNumbers.length - 1; i > 0; i--) { if (charNumbers[i] == '0') { firstOne = i; } else { firstZero = i; } if (firstZero > firstOne) { return swap(charNumbers, firstOne, firstZero); } } return charNumbers; } private char[] swap(char[] cs, int i, int j) { char x = cs[i]; cs[i] = cs[j]; cs[j] = x; return cs; } private static long parseBinaryLong(String s) { return new BigInteger(s, 2).longValue(); } } /* Main.java:3: error: class InterestingSet is public, should be declared in a file named InterestingSet.java public class InterestingSet { ^ 1 error */ |
Double click to view unformatted code.