I’m trying to create a program that will return a certain number decomposed to powers of two. For example 45 would be shown as “2^5 + 2^3 + 2^2 + 2^0”, to do so I converted the number to base 2 and converted it to a string so I could find the index and get the result i wanted. But when trying to return the index all i get is the first index found. Can anyone help me with this part?
import java.util.*;
public class prog{
public static void main(String[] args){
Scanner keyb = new Scanner(System.in);
int val;
System.out.println("Valor");
val = keyb.nextInt();
int aux = val;
while (aux > 0 ){
int num = aux % 2;
aux /= 2;
String dig = String.valueOf(num);
String find = "1";
int index = dig.indexOf(find);
while (index >= 0) {
System.out.println(index);
index = dig.indexOf(find, index + 1);
}
}
}
Your string
digcontains either “0” or “1”.You want this instead:
Note also that this algorithm will print the terms in reverse order compared to your specification.