java - Related to Code Optimization -


i have came across question i'm unable optimize code. please tell me how can optimize code.

    scanner in = new scanner(system.in);     int max=0;     int = in.nextint();     for(int i=1;i<a;i++){         for(int j=i+1;j<=a;j++)         {             int d = i^j;             if(d>max)                 max=d;         }     }     system.out.println(max); 

the explanation above code is:

  • the xor of 1 , 2 3.
  • the xor of 1 , 3 2.
  • the xor of 2 , 3 1.

so, maximum 3.

    scanner in = new scanner(system.in);     int = in.nextint();     system.out.println("max = " + double.tostring(math.pow(2, 1+math.floor(math.log(a)/math.log(2)))-1.0)); 

oops.. doesn't work when a=0, should able adjust that.

explanation

for each possible input a, there number between 1 , a equals not a (considering many binary digits in a itself). so, max equal (2^n)-1, n number of binary digits in a.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -