微乳笔试题-Large Integers,请赐教

kernelkoder 2015-04-07 10:14:41
``````
Large Integers
A 4-byte unsigned integer can only represent values between 0 and 4294967295.
1. Define a class UInteger encapsulating arbitrary non-negative integers, e.g.
123456789123456789123456789123456789.
2. Define and implement a constructor that takes a string containing the hexadecimal representation of an
integer:
UInteger(string numberInHex);
You may assume that the string contains only hex digits and you do not have to check the string’s
validity.
3. Define and implement all relational operators: ==, !=, <, <=, >, >=.
4. Define and implement the addition (+) operator for UIntegers.
``````
...全文
407 5 打赏 收藏 转发到动态 举报

5 条回复

cnmhx 2015-05-21
• 打赏
• 举报

• 打赏
• 举报

``````   public static UInteger operator +(UInteger a, UInteger b)
{
//进位为1
UInt32 C = 0;
string result = string.Empty;

for (int i = 0; i < Math.Max(a.numberInHex.Length, b.numberInHex.Length); i++)
{
UInt32 n1 = a.numberInHex.Length - 1 - i < 0 ? 0 : UInt32.Parse(a.numberInHex.Substring(a.numberInHex.Length - 1 - i, 1), NumberStyles.HexNumber);
UInt32 n2 = b.numberInHex.Length - 1 - i < 0 ? 0 : UInt32.Parse(b.numberInHex.Substring(b.numberInHex.Length - 1 - i, 1), NumberStyles.HexNumber);
result = ((n1 + n2 + C) % 16).ToString("X") + result;
C = (n1 + n2 + C) / 16;
}

UInteger u = new UInteger(C == 0 ? result : "1" + result);

return u;
}``````

• 打赏
• 举报

• 打赏
• 举报

• 打赏
• 举报

`````` class UInteger
{
private   string numberInHex;

public  UInteger(string numberInHex)
{
this.numberInHex = numberInHex;

}

public static bool operator ==(UInteger a, UInteger b)
{

if (System.Object.ReferenceEquals(a, b))
{
return true;
}

if (((object)a == null) || ((object)b == null))
{
return false;
}

return a.numberInHex.ToLower() == b.numberInHex.ToLower();
}

public static bool operator  != (UInteger a, UInteger b)
{

return !(a==b);
}

public static bool operator >(UInteger a, UInteger b)
{
if(a.numberInHex.Count()>b.numberInHex.Count())
return true;
if(a.numberInHex.Count()<b.numberInHex.Count())
return false;
for(int i=0;i<a.numberInHex.Count();i++)
if (a.numberInHex.ToLower().ElementAt(i) > b.numberInHex.ToLower().ElementAt(i))
return true;

return false;
}

public static bool operator <=(UInteger a, UInteger b)
{
return !(a > b);
}

public static bool operator <(UInteger a, UInteger b)
{
if (a.numberInHex.Count() > b.numberInHex.Count())
return false;
if (a.numberInHex.Count() < b.numberInHex.Count())
return true;
for (int i = 0; i < a.numberInHex.Count(); i++)
if (a.numberInHex.ToLower().ElementAt(i) < b.numberInHex.ToLower().ElementAt(i))
return true;

return false;
}

public static bool operator >=(UInteger a, UInteger b)
{
return !(a < b);
}

public static UInteger operator +(UInteger a, UInteger b)
{
UInteger u = new UInteger(a.numberInHex + b.numberInHex);

return u;
}
}``````

33,010

• 近7日
• 近30日
• 至今