标签:
我们知道计算机的数据类型不同,所能表示的数据量级也不相同,比如:
unsigned int : 0~4294967295
int : -2147483648~2147483647
unsigned long : 0~4294967295
long : -2147483648~2147483647
long long : -9223372036854775808 ~ 9223372036854775807
unsigned long long : 0 ~ 18446744073709551615
__int64 : -9223372036854775808 ~ 9223372036854775807
unsigned __int64 : 0 ~ 18446744073709551615
日常的iOS开发工作中使用的数据量级并不会超过上述数据类型,如果是两个大数(比如说:99999999999999999999999999999999999999甚至更多位数的),如何进行计算呢?
下面是我自己用OC写的两个大数相加的算法:
(基本思路是利用字符串模拟两个整数相加的过程)
//两个大数相加算法 -(NSString *)addTwoNumberWithOneNumStr:(NSString *)one anotherNumStr:(NSString *)another { int i = 0; int j = 0; int maxLength = 0; int sum = 0; int overflow = 0; int carryBit = 0; NSString *temp1 = @""; NSString *temp2 = @""; NSString *sums = @""; NSString *tempSum = @""; int length1 = (int)one.length; int length2 = (int)another.length; //1.反转字符串 for (i = length1 - 1; i >= 0 ; i--) { NSRange range = NSMakeRange(i, 1); temp1 = [temp1 stringByAppendingString:[one substringWithRange:range]]; NSLog(@"%@",temp1); } for (j = length2 - 1; j >= 0; j--) { NSRange range = NSMakeRange(j, 1); temp2 = [temp2 stringByAppendingString:[another substringWithRange:range]]; NSLog(@"%@",temp2); } //2.补全缺少位数为0 maxLength = length1 > length2 ? length1 : length2; if (maxLength == length1) { for (i = length2; i < length1; i++) { temp2 = [temp2 stringByAppendingString:@"0"]; NSLog(@"i = %d --%@",i,temp2); } }else{ for (j = length1; j < length2; j++) { temp1 = [temp1 stringByAppendingString:@"0"]; NSLog(@"j = %d --%@",j,temp1); } } //3.取数做加法 for (i = 0; i < maxLength; i++) { NSRange range = NSMakeRange(i, 1); int a = [temp1 substringWithRange:range].intValue; int b = [temp2 substringWithRange:range].intValue; sum = a + b + carryBit; if (sum > 9) { if (i == maxLength -1) { overflow = 1; } carryBit = 1; sum -= 10; }else{ carryBit = 0; } tempSum = [tempSum stringByAppendingString:[NSString stringWithFormat:@"%d",sum]]; } if (overflow == 1) { tempSum = [tempSum stringByAppendingString:@"1"]; } int sumlength = (int)tempSum.length; for (i = sumlength - 1; i >= 0 ; i--) { NSRange range = NSMakeRange(i, 1); sums = [sums stringByAppendingString:[tempSum substringWithRange:range]]; } NSLog(@"sums = %@",sums); return sums; }
算法写的可能不是很简洁,如果你有更好的写法,欢迎在评论区提出,以上所有内容均为本人手打,如需转载请注明出处!
标签:
原文地址:http://www.cnblogs.com/CrazySL/p/5593288.html