For example, I have this code to multiply 2 numbers without using the * symbol, but how can I achieve the same with negative numbers?

public static void main(String[] args) {
    // TODO code application logic here
    Scanner in = new Scanner(System.in);

    int result = 0;

    System.out.println("Enter the first number: ");
    int num1 = in.nextInt();
    System.out.println("Enter the second number: ");
    int num2 = in.nextInt();
   if(num1==0 || num2==0) {
       System.out.println("the profuct of these numbers is: 0");
     }

    for(int i =0; i <num1; i++)

    {
        result += num2;            
    }
    System.out.println("the profuct od these numbers is: "+result);

}

}
有帮助吗?

解决方案 2

If only one number is negative, you can use the same approach, but you need to make sure that you use the positive one in the cycle (as num1 in your code). If both numbers are negative, you can change both of them to positive using abs(num) and nothing changes.

其他提示

java.lang.Maths.abs(num1/2) for iteration and

something like:

if(num1<0^num2<0){
    result = 0 - result;
}

between interation and output.

Keep what you have but keep track of how many negatives you have and use the absolute value.

bool resultNeg = false;
if( num1 < 0 && num2 > 0 || num1 > 0 && num2 < 0 )
    resultNeg = true;

num1 = Math.abs( num1 ); num2 = Math.abs( num2 );

for( int i = 0; i < num1; ++i )
{
    // ...
}

if( resultNeg ) result = 0 - result;

// ...

Maybe BigInteger

BigInteger num1 = new BigInteger(-12);
BigInteger num2 = new BigInteger(-13);
BigInteger result  = num1.multiply(num2);

Also you may use bitwise shifting and adding and try this on negative numbers.

Of course you can mutiply values your way and just make it positive or negative - you know the rules.

public static void main(String[] args)
{
    // TODO code application logic here
    Scanner in = new Scanner(System.in);

    int result = 0;

    System.out.println("Enter the first number: ");
    int num1 = in.nextInt();
    System.out.println("Enter the second number: ");
    int num2 = in.nextInt();
    if(num1==0 || num2==0) {
        System.out.println("the profuct of these numbers is: 0");
        return;
    }

    String sign = "";
    if (num1 < 0 && num2 > 0)
    {
        sign = "-";
    }
    if (num2 < 0 && num1 > 0)
    {
        sign = "-";
    }

    num1 = abs(num1);
    num2 = abs(num2);
    for(int i =0; i <num1; i++)
    {
        result += num2;            
    }
    System.out.println("the profuct of these numbers is: "+sign+result);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top