大数相乘-算法

参考文章

题目

编写两个任意位数的大数相乘的程序,给出计算结果。比如:

题目描述:   输出两个不超过100位的大整数的乘积。
输入: 输入两个大整数,如1234567 和 123
输出: 输出乘积,如:151851741

思路

将每一位相乘,相加的结果保存到同一个位置,到最后才计算进位。
例如:计算98×21,步骤如下
1          9  8
2  ×       2  1
3  -------------
4         (9)(8)  <---- 第1趟: 98×1的每一位结果 
5    (18)(16)     <---- 第2趟: 98×2的每一位结果 
6  -------------
  (18)(25)(8)  <---- 这里就是相对位的和,还没有累加进位 

Objective-C 版


/**
 * 大数相乘方法二
 */
- (NSString *)bigNumberMultiply2:(NSString *)num1 num2:(NSString *)num2 {
    
    NSMutableArray *sumArray = [NSMutableArray array];
    //
    for (int i = 0; i < num1.length; i++){
        NSString *numSubstr1 = [num1 substringWithRange:NSMakeRange(i, 1)];
        
        for (int j = 0; j < num2.length; j++){
            NSString *numSubstr2 = [num2 substringWithRange:NSMakeRange(j, 1)];
            NSInteger index = i + j;

            if (sumArray.count > index) {
                NSString *indexStr = sumArray[index];
                NSString *replaStr = [NSString stringWithFormat:@"%@",@(indexStr.longLongValue + numSubstr1.longLongValue * numSubstr2.longLongValue)];
                [sumArray replaceObjectAtIndex:index withObject:replaStr];
            } else {
                NSString *replaStr = [NSString stringWithFormat:@"%@",@(numSubstr1.longLongValue * numSubstr2.longLongValue)];
                [sumArray addObject:replaStr];
            }
        }
    }
    
    //单独处理进位
    for(NSInteger k = sumArray.count - 1; k > 0; k--){
        NSString *indexStr = sumArray[k];

        if(indexStr.longLongValue > 10){
            NSString *indexStrd1 = sumArray[k-1];
            NSString *indexStr11 = [NSString stringWithFormat:@"%@",@(indexStrd1.longLongValue + indexStr.longLongValue / 10)];
            [sumArray replaceObjectAtIndex:k-1 withObject:indexStr11];
            [sumArray replaceObjectAtIndex:k withObject:[NSString stringWithFormat:@"%@",@(indexStr.longLongValue % 10)]];
        }
    }
    
    // 处理数组第一个数
    if (sumArray.count) {
        NSString *indexStr = sumArray[0];
        if(indexStr.longLongValue > 10){
            NSString *indexStr11 = [NSString stringWithFormat:@"%@",@(indexStr.longLongValue / 10)];
            [sumArray insertObject:indexStr11 atIndex:0];
            if (sumArray.count > 1) {
                [sumArray replaceObjectAtIndex:1 withObject:[NSString stringWithFormat:@"%@",@(indexStr.longLongValue % 10)]];
            } else {
                [sumArray addObject:[NSString stringWithFormat:@"%@",@(indexStr.longLongValue % 10)]];
            }
        }
    }
   
    NSMutableString *sumString = [NSMutableString string];
    for (NSString *str in sumArray) {
        [sumString appendString:str];
    }
    NSLog(@"%@ * %@ = %@",num1,num2,sumString);
    
    return sumString;
}

swift 版 待更新

你可能感兴趣的:(大数相乘-算法)