2020年3月20日 星期五

2.2-Adding_Large_Numbers - lab

解題心得:
其實不是很了解為啥規定用struct寫。這題本質就是大數運算。
我add function因為怕時間內做不完當時是先拿下面網址的code改來用,之後有空應該會重新寫一次......
reference:How to get the sum of two strings of numbers - C++

程式碼:
#include <iostream>
#include <string>
using namespace std;

struct BigInt
{
 string numberArray;
 int length;
};
BigInt Add(const BigInt &na, const BigInt &nb)
{
 string a = na.numberArray, b = nb.numberArray;
 if (a.size() < b.size()) // make sure a is always longer.
  swap(a, b);
 int j = a.size() - 1;
 for (int i = b.size() - 1; i >= 0; i--, j--) // 從個位數開始相加
  a[j] += (b[i] - '0');

 for (int i = a.size() - 1; i > 0; i--)
 {
  if (a[i] > '9') // make sure each digit is smaller than 10
  {
   int d = a[i] - '0';
   a[i - 1] = ((a[i - 1] - '0') + d / 10) + '0';
   a[i] = (d % 10) + '0';
  }
 }
 if (a[0] > '9') // 如果最高位需要進位的處理
 {
  string k;
  k += a[0];
  a[0] = ((a[0] - '0') % 10) + '0'; // 取個位數
  k[0] = ((k[0] - '0') / 10) + '0'; // 取十位數
  a = k + a; // append
 }
 BigInt result;
 result.numberArray = a;
 return result;
  
 
}
int checkInput(string &number)
{
 int check = 0;// if check is 1, then it is invalid input.
 for (int i = 0; i < number.size(); i++)
 {
  if (!isdigit(number[i]))
  {
   return 1;
  }
 }
 return 0;
}
int main() {
 BigInt a, b, result;
 string n1, n2;
 int n;
 while (cin >> n)
 {
  for (int i = 0; i < n; i++) // input data
  {
   cin >> n1 >> n2;
   if (checkInput(n1) || checkInput(n2))
   {
    cout << "Not a valid number, please try again." << endl;
    continue;
   }
   a.numberArray = n1;
   a.length = n1.size();
   b.numberArray = n2;
   b.length = n2.size();
   result = Add(a, b);
   cout << result.numberArray << endl;
  }
 }
    return 0;
}

補上自己重寫一遍的程式碼
#include <iostream>
#include <string>
using namespace std;

struct BigInt
{
 string number;
};

BigInt add(BigInt &a, BigInt &b)
{
 string n1 = a.number, n2 = b.number;
 if (n1.size() < n2.size())
  swap(n1, n2);
 int len1 = n1.size(), len2 = n2.size(), j = len1-1; // j is bottom index of n1

 for (int i = len2-1; i >= 0; i--, j--) // 把n2先直接加上n1
 {
  n1[j] += (n2[i] - '0');
 }
 for (int i = len1 - 1; i > 0; i--) // 除了 index 0 ,其餘都檢查是否需要進位
 {
  if (n1[i] > '9')
  {
   n1[i] = (n1[i] - '0') % 10 + '0';
   n1[i - 1] += 1;
  }
 }

 if (n1[0] > '9')
 {
  string append = "1";
  n1[0] = (n1[0] - '0') % 10 + '0';
  append = append + n1;
  n1 = append;
 }
 BigInt result;
 result.number = n1;
 return result;
}

int checkInput(string numberArray)
{
 for (int i = 0; i < numberArray.size(); i++)
 {
  if (!isdigit(numberArray[i]))
   return 0;
 }
 return 1;
}
int main()
{
 BigInt a, b;
 while (cin >> a.number >> b.number)
 {
  if (checkInput(a.number) && checkInput(b.number))
  {
   BigInt result = add(a, b);
   cout << result.number << endl;
  }
  else
   cout << "Not a valid number, please try again." << endl;
 }
 
 return 0;
}

沒有留言:

張貼留言