We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Java - How can I look at a problem and find the most simple solution?
Is there a guideline on what to think about before coding. For example, logical operators first?
publicstaticlongflippingBits(longn){// Convert to binarylongq=n;Stringbinary="";while(q>0){longremainder=q%2;binary=remainder+binary;q=q/2;}System.out.println("Binary of "+n+" = "+binary);// Calculate how many zeros to add at the start to get 32-bitintzerosToAdd=32-binary.length();StringpaddedBinary="0".repeat(zerosToAdd)+binary;System.out.println("32-bit padded: "+paddedBinary);// Flip the bitsStringBuilderflipped=newStringBuilder();for(inti=0;i<paddedBinary.length();i++){if(paddedBinary.charAt(i)=='0'){flipped.append('1');}else{flipped.append('0');}}// Convert StringBuilder to StringStringflippedStr=flipped.toString();// Parse as base-2longdecimal=Long.parseLong(flippedStr,2);returndecimal;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Flipping bits
You are viewing a single comment's thread. Return to all comments →
Java - How can I look at a problem and find the most simple solution? Is there a guideline on what to think about before coding. For example, logical operators first?