Skip to content

Commit

Permalink
Add addition without arithmetic algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagohpr committed Oct 18, 2024
1 parent 36a7dd6 commit 64f2f42
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Algorithms.Tests/Numeric/AdditionWithoutArithmeticsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Numerics;
using Algorithms.Numeric;
using NUnit.Framework;

namespace Algorithms.Tests.Numeric;

public static class AdditionWithoutArithmeticTests
{
[TestCase(3, 5, 8)]
[TestCase(13, 5, 18)]
[TestCase(-7, 2, -5)]
[TestCase(0, -7, -7)]
[TestCase(-321, 0, -321)]
public static void CalculateAdditionWithoutArithmetic_Test(int first, int second, int expectedResult)
{
// Act
var result = AdditionWithoutArithmetic.CalculateAdditionWithoutArithmetic(first, second);

// Assert
Assert.That(result, Is.EqualTo(expectedResult));
}
}
27 changes: 27 additions & 0 deletions Algorithms/Numeric/AdditionWithoutArithmetic.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Numerics;

namespace Algorithms.Numeric;

/// <summary>
/// Add the integers without arithmetic operation.
/// </summary>
public static class AdditionWithoutArithmetic
{
/// <summary>
/// Returns the sum of two integers.
/// </summary>
/// <param name="first">First number to add.</param>
/// <param name="second">Second number to add.</param>
/// <returns>Sum of the two numbers.</returns>
public static int CalculateAdditionWithoutArithmetic(int first, int second)
{
while (second != 0)
{
int c = first & second; // Carry
first ^= second; // Sum without carry
second = c << 1; // Carry shifted left
}

Check failure on line 24 in Algorithms/Numeric/AdditionWithoutArithmetic.cs

View workflow job for this annotation

GitHub Actions / build

Check failure on line 24 in Algorithms/Numeric/AdditionWithoutArithmetic.cs

View workflow job for this annotation

GitHub Actions / build

return first;
}
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ find more than one implementation for the same objective but using different alg
* [Modular Multiplicative Inverse](./Algorithms/ModularArithmetic/ModularMultiplicativeInverse.cs)
* [Numeric](./Algorithms/Numeric)
* [Absolute](./Algorithms/Numeric/Abs.cs)
* [Addition Without Arithmetic](./Algorithms/Numeric/AdditionWithoutArithmetic.cs)
* [Aliquot Sum Calculator](./Algorithms/Numeric/AliquotSumCalculator.cs)
* [Amicable Numbers Checker](./Algorithms/Numeric/AmicableNumbersChecker.cs)
* [Decomposition](./Algorithms/Numeric/Decomposition)
Expand Down

0 comments on commit 64f2f42

Please sign in to comment.