How can I perform multiplication without the '*' operator?

前端 未结 30 1588
别跟我提以往
别跟我提以往 2020-12-01 01:47

I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it\'s like this

<
30条回答
  •  不知归路
    2020-12-01 02:43

    package com.amit.string;
    
    // Here I am passing two values, 7 and 3 and method getResult() will
    // return 21 without use of any operator except the increment operator, ++.
    //
    public class MultiplyTwoNumber {
    
        public static void main(String[] args) {
            int a = 7;
            int b = 3;
            System.out.println(new MultiplyTwoNumber().getResult(a, b));
        }
    
        public int getResult(int i, int j) {
            int result = 0;
    
            // Check for loop logic it is key thing it will go 21 times
            for (int k = 0; k < i; k++) {
                for (int p = 0; p < j; p++) {
                    result++;
                }
            }
            return result;
        }
    }
    

提交回复
热议问题