小算法集锦 : 20行代码实现大数相乘

1.大数相乘

1.1 js 版本 (不计算注释只需要20行)

   /**
   * 大数乘法
   * 思路:逐位相乘,不算进位;最后算进位并拼接字符串
   * @param {number} a 被乘数
   * @param {number} b 乘数
   */
  var LargeNumberTimes = function (a, b) {
    var result = []
    // 转换为整型数组
    a = a.toString().split('').map(t => parseInt(t))
    b = b.toString().split('').map(t => parseInt(t))
    // 逐位相乘,不算进位,与计算方向无关
    for (var i = 0; i < b.length; i++) {
      for (var j = 0; j < a.length; j++) {
        if (!result[i + j])
          result[i + j] = 0
        result[i + j] += b[i] * a[j]
      }
    }
    // 右边的高位向左边低位进位, 在0处无需进位
    for (var i = result.length - 1; i > 0; i--) {
      var more = parseInt(result[i] / 10)
      if (more > 0) {
          result[i - 1] += more;
      }
      result[i] = result[i] % 10;
    }
    return result.join('');
  };

  // 可在 Google 输入框进行验证,如果输入的乘数大小超过了范围
  // (或js会转换为科学计数法),需要以字符串传入
  // Result: 999999999998000000000001
  //console.log( LargeNumberTimes(999999999999, 999999999999) );

1.2 C语言 大数相乘 无依赖

#include 
#define max_length 1000
int strlen(char *a){
    int i;
    for( i=0; a[i] != '\0' ;i++);
    return i;
}
void printIntArray(int a[]){
    for(int i=0;i=0; bIndex--) {
        for (int aIndex=aLen-1; aIndex>=0; aIndex--) {
            if(resultInt[bIndex + aIndex] == -1) {
                resultInt[bIndex + aIndex] = 0 ;
            }
            resultInt[bIndex + aIndex] += bArr[bIndex] * aArr[aIndex];
        }
    }
    printIntArray(resultInt);
    int resultLength =0;
    for(int i =0;i 0) {
            if(i+1 >= resultLength){
                resultLength ++ ;
            }
            if(resultInt[i+1] == -1) {
                resultInt[i+1] = 0 ;
            }
            resultInt[i + 1] += more;
        }
        resultInt[i] = resultInt[i] % 10;
    }
    char resultStr[max_length*2] ;
    for(int  i = 0; i< resultLength ; i++){
        resultStr[i] = resultInt[resultLength-1-i] + '0';
    }
    resultStr[resultLength] = '\0';
    printf("%s\n",resultStr);
    return resultStr;
}

int main(){
    printf("hello\n");
    printf("%s\n", LargeNumberTimes("5000000", "5000000"));
}

简单的 js 转 c 想法:

  • 函数之间参数传递用 char * ,内部接收后再转 int 计算
  • undefined+ 动态数组 : 使用一个较大的数组初始化为-1,延长长度时就把-1改为0

2. 阿拉伯数字和英文互转

/* 数字转英文 */
function numToEn(str){
    str = str + ''
    var s3 = ['','thousand','million','billion']
    var res = []
    while(str > 0){
        res.push(s3.shift())
        res.push(below1000(str.slice(-3)))
        str = str.slice(0,-3)
    }
    return res.reverse().join(' ')
    
}
function below1000(str){
        str = str - 0;
        var under20 = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty']
        var res = '';
        if(str / 100 >=1) res += under20[Math.floor(str/100)] + " hundred and";
        str = str % 100 
        
        if(str > 20){
            var ten = Math.floor(str / 10)
            res += ' ' + ['','',"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"][ten]
            res += ' ' + under20[str % 10]
        }else { res += ' ' + under20[str] }
        return res;
    }
/* 英文转数字 */
function enToNum(str){
    str = str.split(/\s+/).concat('$')
    var under20Map = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'].reduce((sum,x,index)=>{ sum[x]=index; return sum }, {})
    var s3Map = ['$','thousand','million','billion'].reduce((sum,x,index)=>{ sum[x]=Math.pow(1000,index); return sum }, {})
    var tensMap = ['','ten',"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"].reduce((sum,x,index)=>{ sum[x]=index*10; return sum }, {})
    var res = 0, now = 0
    str.forEach(x=>{
        if(x === "hundred") now *= 100
        if(x in tensMap) now += tensMap[x]
        else if(x in under20Map) now += under20Map[x]
        if(x in s3Map){
            res += now*s3Map[x]
            now = 0
        }
    })
    return res 
}
/* 测试代码 */
function test(count = 10){
    window.logs = []
    window.errors = []
    for(var i=0;i

字符串格式如下图, 可自行对其中空格或逗号进行增删


小算法集锦 : 20行代码实现大数相乘_第1张图片

你可能感兴趣的:(小算法集锦 : 20行代码实现大数相乘)