(Karatsuba算法的 C++实现) Coursera 斯坦福大学 算法课程 Programming Assignment #1

这篇博客详细介绍了在Coursera斯坦福大学算法课程中的编程作业,涉及Karatsuba算法的C++实现,专注于单个数字的乘法。文章提醒读者限制输入为64位数字,并提供了测试用例。讨论了编程中可能遇到的陷阱,如字符串对齐、添加和减法操作,以及如何有效使用string类的方法。
摘要由CSDN通过智能技术生成

Divide and Conquer, Sorting and Searching, and Randomized Algorithms

题目

In this programming assignment you will implement one or more of the integer multiplication algorithms described in lecture.

To get the most out of this assignment, your program should restrict itself to multiplying only pairs of single-digit numbers. You can implement the grade-school algorithm if you want, but to get the most out of the assignment you’ll want to implement recursive integer multiplication and/or Karatsuba’s algorithm.

So: what’s the product of the following two 64-digit numbers?

3141592653589793238462643383279502884197169399375105820974944592

2718281828459045235360287471352662497757247093699959574966967627

[TIP: before submitting, first test the correctness of your program on some small test cases of your own devising. Then post your best test cases to the discussion forums to help your fellow students!]

[Food for thought: the number of digits in each input number is a power of 2. Does this make your life easier? Does it depend on which algorithm you’re implementing?]

The numeric answer should be typed in the space below. So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks.

(We do not require you to submit your code, so feel free to use any programming language you want — just type the final numeric answer in the following space.)

程序

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void addZeros(string &num1, string&num2){
   
    int l1 = num1.size();
    int l2 = num2.size();
    if(l1 > l2){
   
        for(int i = 0; i < l1 - l2; i++){
   
            num2 = ('0' + num2);
        }
    }else{
   
        for(int i = 0; i < l2 - l1; i++){
   
            num1 = ('0' + num1);
        }
    }
}

string stringPlus(string num1, string num2){
   
    int carrier = 0;
    int bitresult = 0;
    string fullResult;
    string finalResult;
    addZeros(num1,num2);
    for(int i =0; i < num1.size(); i++){
   
        bitresult = num1[num1
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值