fork download
  1. import java.util.*;
  2.  
  3. class Power2 {
  4. public static void main(String[] args){
  5. Scanner in = new Scanner(System.in);
  6. int valor = 0;
  7. int resto;
  8. int[] myArray=new int[31];
  9. int ndivisoes = 0;
  10.  
  11. System.out.println( "Valor [1..2^31] ?");
  12. valor = in.nextInt();
  13. System.out.println( valor );
  14.  
  15. while( valor > 0 ){
  16. resto = valor % 2;
  17. valor /= 2;
  18. System.out.println( "resto = " + resto + " / valor = " + valor );
  19. myArray[ndivisoes++] = resto;
  20. }
  21.  
  22. String soma = "";
  23. for( int j = ndivisoes; j >= 0; j-- ){
  24. if( myArray[j] == 1 ){
  25. System.out.print( soma + "2^" + j );
  26. soma = " + ";
  27. }
  28. }
  29. }
  30. }
Success #stdin #stdout 0.11s 380736KB
stdin
27

stdout
Valor [1..2^31] ?
27
resto = 1 / valor = 13
resto = 1 / valor = 6
resto = 0 / valor = 3
resto = 1 / valor = 1
resto = 1 / valor = 0
2^4 + 2^3 + 2^1 + 2^0