Add sum without using any mathematical operators (#3473)

This commit is contained in:
samratpodder 2022-10-10 22:49:01 +05:30 committed by GitHub
parent 40dc1c483d
commit 8661d07276
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package com.thealgorithms.maths;
public class SumWithoutArithmeticOperators {
/**
* Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /).
* All the integers associated are unsigned 32-bit integers
*https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator
*@param a - It is the first number
*@param b - It is the second number
*@return returns an integer which is the sum of the first and second number
*/
public int getSum(int a, int b){
if(b==0) return a;
int sum = a^b;
int carry = (a&b)<<1;
return getSum(sum, carry);
}
}

View File

@ -0,0 +1,39 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class SumWithoutArithmeticOperatorsTest {
SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators();
@Test
void addZerotoZero(){
assertEquals(0,obj.getSum(0, 0));
}
@Test
void addZerotoNumber(){
assertEquals(5,obj.getSum(0, 5));
assertEquals(28,obj.getSum(28, 0));
}
@Test
void addOddtoEven(){
assertEquals(13,obj.getSum(3, 10));
assertEquals(55,obj.getSum(49, 6));
}
@Test
void addEventoOdd(){
assertEquals(13,obj.getSum(10, 3));
assertEquals(41,obj.getSum(40, 1));
}
@Test
void addRandoms(){
assertEquals(88,obj.getSum(44, 44));
assertEquals(370,obj.getSum(100, 270));
assertEquals(3,obj.getSum(1, 2));
assertEquals(5,obj.getSum(2, 3));
}
}