How to get the last more "+" that appears on the console from this code?

Asked

Viewed 138 times

2

Can anyone tell me how to get the last "+" that appears on the console from this code:

import java.util.Scanner;
public class Power2 {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Valor [1..2^31] ?"); 
        int valor = input.nextInt();
        for(int i=0;valor<0;i++){
            System.out.println("Valor [1..2^31] ?"); 
            valor=input.nextInt();
        }
        int[] array=new int[31];
        int[] arrayvalor=new int[31];
        int resto;
        int ndivisoes=0;

        for(int i=0;valor>0;i++){    
            resto=(valor%2);
            System.out.println("resto= "+resto);
            valor=valor/2;
            System.out.println(valor);
            array[i]=resto;
            ndivisoes=i;
            arrayvalor[i]=valor;
            //System.out.println(arrayvalor[i]);
            //System.out.println("i= "+i);
        }
        int count=ndivisoes;

        for(int j=ndivisoes;j>=0;j--){
            String soma=" ";
            if(array[j]==1){
                if(j==0){
                    soma=" ";
                    System.out.print(2+"^"+j+soma);    
                }else{
                    soma="+";
                    System.out.print(2+"^"+j+soma);

                }                      
            }
        }
    }
}

4 answers

2


Simplified solution:

   ...
}
int count=ndivisoes;
// Mantive a linha acima, que não é usada, apenas para você ver de onde eu comecei o código.

String soma="";
for(int j=ndivisoes;j>=0;j--){
    if(array[j]==1){
        System.out.print(soma+"2^"+j);
        soma="+"; // por estética pode usar soma=" + "; se preferir
    }
}

Click here to see the result in IDEONE.

  • For 6 the result was 2^2+2^1+ with the + at the end. Nothing is missing from the code?

  • 2

    @Lucasnunes with this code that I posted, it is impossible a "+" at the end. Make sure to copy and paste it in its entirety to test.

0

From what I understand of your code, it works well when the lowest value of j for which array[j] == 1 is 0, and works badly (displays the + a further) when the smaller j for which array[j] == 1 is > 0.

So you really don’t want to use the condition if (j == 0), and yes if (j == x) where x is the lowest value of j for which array[j] == 1.

My suggestion is that you create a method that you receive as a parameter array and returns the lowest position of array for which array[posição] == 1, and use this result in your if.

I don’t know if my logic is the best way to do it, but it illustrates the problem and you can work on the code to improve it from what this logic is evidencing.

0

You can solve this problem by not adding + and instead add spaces. Then you make a trim() to remove possible spaces after the value and replace the spaces by +.

I did the following here:

    String soma=" ";

    for(int j=ndivisoes;j>=0;j--)
    {
        if(array[j]==1)
        {
            soma += "2^" + j + " ";
        }
    }

    soma = soma.trim();
    soma = soma.replace(' ', '+');
    System.out.println(soma);

The exit was:

Valor [1..2^31] ?
6
resto= 0
3
resto= 1
1
resto= 1
0
2^2+2^1

0

There’s no guarantee that array[j] == 1 in the last loop iteration, and this is the necessary condition for you to set the variable soma as " ".

My approach to the problem considers as a special case the first impression on the exit and not the last. Because we know that after something has already been sent to the screen we can put a "+" ahead of the next things we’ll print.

That way just use a flag to signal us when something was printed.

See the fixed algorithm:

boolean foiImpresso = false;
for (int j = ndivisoes; j >= 0; j--) {
    if (array[j] == 1) {
        if (foiImpresso) {
            System.out.print(" + 2^" + j);
        } else {
            System.out.print("2^" + j);
            foiImpresso = true;
        }
    }
}

See that the variable soma was not used as it is completely unnecessary. Note that I have not tested this algorithm, I am just assuming that it is correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.