Untitled

 avatar
unknown
c_cpp
a year ago
1.6 kB
2
Indexable
import java.io.*;
import java.util.*;

class Main {
    
    public static int nextSameTasteNumber(int n) {
        int c = n;
        int c0 = 0;
        int c1 = 0;
        
        while (((c & 1) == 0) && (c != 0)) {
            c0++;
            c >>= 1;
        }
        
        while ((c & 1) == 1) {
            c1++;
            c >>= 1;
        }
        
        if (c0 + c1 == 0 || c0 + c1 == 31) {
            return -1; // Error case
        }
        
        int p = c0 + c1; // Position of rightmost non-trailing zero
        
        n |= (1 << p); // Flip the rightmost non-trailing zero
        n &= ~((1 << p) - 1); // Clear all bits to the right of p
        n |= (1 << (c1 - 1)) - 1; // Insert (c1-1) ones on the right
        
        return n;
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> inputByLine = new ArrayList<String>();
        
        try (
            InputStreamReader isr = new InputStreamReader(System.in, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
        ) {
            String line;
            while ((line = br.readLine()) != null) {
                inputByLine.add(line);
            }
            
            for (int i = 1; i < inputByLine.size(); i++) {
                int N = Integer.parseInt(inputByLine.get(i));
                System.out.println(nextSameTasteNumber(N));
            }
            
            isr.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}