Today morning, I was on a coding website and saw a question about adding two numbers without using the + symbol. I started thinking about that problem. I am sure that it can be done by using some binary operations. But I am not good at binary operations. I was thinking of loops to get that and figure out that logic. But I'd like to use some basic math concepts to solve this. I took a piece of paper and tried a simple addition operation. I was thinking about squaring, subtracting, and multiplying the numbers. Later, I found that first we can subtract the two numbers, then multiply a number by 2, and finally subtract the value from our initial subtracted value. Later that day, I considered what would happen if a negative number or some other constraint came up. Then I began to think about it again. After some time, I found a way to fix it. Here's how it can be fixed:
Find the maximum value and minimum value between the two numbers, then multiply the maximum number by 2, subtract the maximum and minimum values, and finally subtract the multiplied value and the subtracted value to add the numbers. I understand that this is a long way to add numbers, but I discovered it and wanted to share it. By the way, this is the first time I've shared my thoughts. Kindly acknowledge any mistakes I have made. Thank you.
Here is the code for that.
public class add{
public static void main(String [] args){
int a = 10, b = 20;
// finding the maximum and minimum value
int max_value = Math.max(a,b);
int min_value = Math.min(a,b);
// to find the subtracted value
int sub_value = max_value - min_value;
// to find the multiplied value
int mul_value = max_value * 2;
// to find the answer
int ans = mul_value - sub_value;
System.out.println("The answer is " + ans);
}
}
/* Output
The answer is 30 */