Add spaces in a String using Java

If u would like to print String "123" as "1 2 3" then follow this code.


yourString.replace("", " ").trim();
Above code just replacing all empty place with Space & remove starting space with trim           method




Add leading zeros for binary conversion in java

If u convert Decimal 15 to binary,you will get  Binary 1110 So you may want to add leading zero Ex:00001110

Step1:Find how many zeros do you need ?

if your input is16 then log2 16=4 zeros
if your input is 15 then log2 15=3 zeros not correct :-) So check 3 mod 2  !=0 and add one to it 3+1=4



int zeros=0;        
zeros=(int) (Math.log(input)/ Math.log(2));
if (zeros%2!=0) zeros=zeros+1;


Step2:Add these zeros to your binary output


String formatted=String.format("%0"+zeros+"d\n", Integer.parseInt(Integer.toBinaryString(count)));
System.out.println(formatted);








logarithm base 2 calculation in java

By default java provides base 10 using In build Math class


Base 10 log


Math.log(input) ;


Base 2 log


Math.log(input) / Math.log(2);


This methods will return values in double so if you need integer 

int zeros=(int) (Math.log(input)/ Math.log(2));






^ Top