Problem 33 question about solution

Back to Problem Solutions forum

shatseli     2020-04-05 04:28:51

Hi Rodion Please kindly hint me what may be wron with my approach ( I simply caqnnot figure out more :-( )

My code ( pls. see below ) : 1. counts a number of bits set to 1 2. if this number of is odd - goes to the next value (skips the futher steps) 3. if the hightmost bit set to 1 clears it to 0 4. convert resulting value to char

thank you in advance !

do { try { int n = scan.nextInt(); // bt = (byte)n ; String str = Integer.toBinaryString(n);

           // counts amount of bit(1)
           int bitcount = 0;
           for ( int i = 0; i<str.length();i++)
               if ( str.valueOf(i) == "1" ) bitcount ++;

            // checks the task condition for even amount of bits set to 1    
           if ( bitcount%2 == 0 ) 
           {
                    // masking hight rightmost bit
                if ( str.length() == 8  &&  str.charAt(0) == '1' )
                   n = n & 0b01111111;
                ch = (char)n ;
                System.out.print( ch );  
           }

} while ( hasNextInt());

shatseli     2020-04-05 12:30:51

Hi Rodion No need to reply : I've found the reason of my bug :-) ... If it possible just gave me a few crytical notes about my source ...

Rodion (admin)     2020-04-10 03:09:33
User avatar

Hi Eli!

I'm quite glad you was able to pinpoint the bug yourself due to my delay :)

It was almost intentionally! I do believe bugs we found ourselves teach us 10 times more!

If it possible just gave me a few crytical notes about my source

Well, probably the most significant issue is that one definitely don't need conversion of number to binary string in this problem! You yourself use bit arithmetic at one place n = n & 0b01111111 - and you just need to use it in other places :)

In other respects all is well, hm-m-m, except things about style (yes, again, sorry):

  • code for working with single number n should be extracted to separate function, definitely, all these nested blocks don't give good impression;
  • and Java Coding Conventions should be respected, well, as Torah or Bible among java programmers :)
Please login and solve 5 problems to be able to post at forum