Skip to content

Commit bd2d09d

Browse files
authored
Add addition without + operator(#482)
1 parent fe93f57 commit bd2d09d

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System;
2+
using System.Numerics;
3+
using Algorithms.Numeric;
4+
using NUnit.Framework;
5+
6+
namespace Algorithms.Tests.Numeric;
7+
8+
public static class AdditionWithoutArithmeticTests
9+
{
10+
[TestCase(3, 5, 8)]
11+
[TestCase(13, 5, 18)]
12+
[TestCase(-7, 2, -5)]
13+
[TestCase(0, -7, -7)]
14+
[TestCase(-321, 0, -321)]
15+
public static void CalculateAdditionWithoutArithmetic_Test(int first, int second, int expectedResult)
16+
{
17+
// Act
18+
var result = AdditionWithoutArithmetic.CalculateAdditionWithoutArithmetic(first, second);
19+
20+
// Assert
21+
Assert.That(result, Is.EqualTo(expectedResult));
22+
}
23+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
using System.Numerics;
3+
4+
namespace Algorithms.Numeric;
5+
6+
/// <summary>
7+
/// Add the integers without arithmetic operation.
8+
/// </summary>
9+
public static class AdditionWithoutArithmetic
10+
{
11+
/// <summary>
12+
/// Returns the sum of two integers.
13+
/// </summary>
14+
/// <param name="first">First number to add.</param>
15+
/// <param name="second">Second number to add.</param>
16+
/// <returns>Sum of the two numbers.</returns>
17+
public static int CalculateAdditionWithoutArithmetic(int first, int second)
18+
{
19+
while (second != 0)
20+
{
21+
int c = first & second; // Carry
22+
first ^= second; // Sum without carry
23+
second = c << 1; // Carry shifted left
24+
}
25+
26+
return first;
27+
}
28+
}

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ find more than one implementation for the same objective but using different alg
6767
* [Extended Euclidean Algorithm](./Algorithms/ModularArithmetic/ExtendedEuclideanAlgorithm.cs)
6868
* [Modular Multiplicative Inverse](./Algorithms/ModularArithmetic/ModularMultiplicativeInverse.cs)
6969
* [Numeric](./Algorithms/Numeric)
70-
* [Absolute](./Algorithms/Numeric/Abs.cs)
70+
* [Absolute](./Algorithms/Numeric/Abs.cs)
71+
* [Addition Without Arithmetic](./Algorithms/Numeric/AdditionWithoutArithmetic.cs)
7172
* [Aliquot Sum Calculator](./Algorithms/Numeric/AliquotSumCalculator.cs)
7273
* [Amicable Numbers Checker](./Algorithms/Numeric/AmicableNumbersChecker.cs)
7374
* [Decomposition](./Algorithms/Numeric/Decomposition)

0 commit comments

Comments
 (0)