java - Maximum Value of XOR in a range? -


given matrix of size nxn. rows , columns numbered 0 n-1. jth column of ith row contains xor j. in other words, matrix[i][j] = ^ j 0 ? i,j < n. task find maximum value occurring in matrix , count of occurrence.

while approach

(l..r).each |i|     (i..r).each |j|       if (i ^ j > max)         max = ^ j       end     end   end 

i saw code says according not quadratic finding in linear time.

public static void main(string[] args) throws exception {         bufferedreader br = new bufferedreader(new inputstreamreader(system.in));          long n;         long max    = 1l;         long count  = 1l;         long bitn   ;         stringbuilder sb  = new stringbuilder(4*t);               line = br.readline();             n = long.parselong(line);             {                  bitn    = 1l << getbits(n-1);                 max     = (bitn - 1);                 count   = (bitn == n) ? bitn :(n -(bitn>>1))<<1 ;                  sb.append(max);                 sb.append(" ");                 sb.append(count);                 sb.append("\n");             }          system.out.println(sb.tostring());     }      private static int getbits(long x){         int count = 0;         while(x > 0){             x = x>>1;             count++;         }         return count;     } }  

what i'm unable understand how

bitn    = 1l << getbits(n-1); max     = (bitn - 1); count   = (bitn == n) ? bitn :(n -(bitn>>1))<<1 ; 

able desired result. if of give me basic of algorithm in simple terms can understand

make table of n versus max , count:

n   max   count   how 1     0       1   0^0 2     1       2   0^1, 1^0 3     3       2   1^2, 2^1 4     3       4   1^2, 2^1, 0^3, 3^0 5     7       2   3^4, 4^3 6     7       4   3^4, 4^3, 2^5, 5^2 7     7       6   3^4, 4^3, 2^5, 5^2, 1^6, 6^1 8     7       8   3^4, 4^3, 2^5, 5^2, 1^6, 6^1, 0^7, 7^0 9    15       2   7^8, 8^7 . . 

the pattern that, after n crosses power of two, max goes , count goes 2. because bit patterns this:

3 = 0b011 4 = 0b100 . . 7 = 0b0111 8 = 0b1000 

bitn lowest bit set in 0..n-1 (so bitn = 8 when n = 8, , bitn = 16 when n = 9). maximum xor has bits below bitn set, bitn - 1 logic of borrowing in grade-school subtraction. count goes 2 every time n increases 1 except when bitn increases well, when count resets two. purpose of ternary operator in computing count special case n = 1; left branch taken when n greater power of two, other work well.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -