Problem
Implement C# function
int addone(int n)
which will return n+1. You can NOT use any of the following arithmetical operations in the fuction body: + - * / ++ -- += -=
.Solution
using NUnit.Framework;
namespace Developer.Test.Net
{
[TestFixture]
public class TestModulus
{
[Test]
public void TestAddOne()
{
for (int i = -1000; i < 1000; i++)
{
Assert.AreEqual(i + 1, AddOne(i));
}
int j = int.MaxValue;
Assert.AreEqual(j + 1, AddOne(j));
j = int.MinValue;
Assert.AreEqual(j + 1, AddOne(j));
}
public static int AddOne(int n)
{
int position = 1;
while (position != 0)
{
if ((n & position) == position) {
n = n ^ position;
} else {
n = n | position;
break;
}
position = position << 1;
}
return n;
}
}
}
0 комментария(ев):
Post a Comment