Matlab实现两个大数相加

对自己很是无语!

function D = strAdd(str1)
    n1 = length(str1);
    n2 = length(str2);
    flag = 0;
    D = [];
    while n1 >= 1 & n2 >= 1

      a = str2double(str1(n1));
      b = str2double(str2(n2));
      c = mod(a + b + flag,10);
      flag = floor((a + b + flag) / 10);
      D = [D,c];
      n1 = n1 - 1;
      n2 = n2 - 1;
    end
    while n1 >= 1 
        a = str2double(str1(n1));
        c = mod(a + flag,10);
        flag = floor((a + flag) / 10);
        D = [D,c];
        n1 = n1 - 1;
    end
    while n2 >= 1 
        a = str2double(str2(n2));
        c = mod(a + flag,10);
        flag = floor((a + flag) / 10);
        D = [D,c];
        n2 = n2 - 1;
    end
    if flag > 0

        D = [D,flag];

    end
    D = D(end : -1 :1);
end


猜你喜欢

转载自blog.csdn.net/anan1205/article/details/50889455