划分的bigint在字符串中呈现为2

Dividing bigint presented in string to 2

本文关键字:字符串 bigint 划分      更新时间:2023-10-16

我正在编写一个函数,该函数将字符串中显示的大int(128位)数除以2。例如:8113是字符串=" 8113"我知道我的功能错误在情况下du!= 0。请给我一些建议。如果我的算法太糟糕了,请告诉我更好,那么我可以以另一种方式更改我的功能。

int CTOI(char a)
{
    return a - 48;
}
char ITOC(int a)
{
    if (a == 0)
        return '0';
    return a + '0';
}
int creDec(int a, int b)
{
    return (a * 10) + b;
}
string divide2(string str)
{
    string temp = str, t2;
    int du, kq;
    du = CTOI(temp[0]);
    if (du == 1) {
        temp.erase(0, 1);
        while (temp[0] != 0)
        {
            du = creDec(du, CTOI(temp[0]));
            if (du == 1)
            {
                temp.erase(0, 1);
            }
            else
                temp.erase(0, 1);
            kq = du / 2;
            t2 += ITOC(kq);
            du = du - kq * 2;
        }
    }
    else
    {
        while (temp[0] != 0)
        {
            if (du == 1)
            {
                temp.erase(0, 1);
                du = creDec(du, CTOI(temp[0]));
            }
            kq = du / 2;
            t2 += ITOC(kq);
            du = du - kq * 2;
            temp.erase(0, 1);
            du = creDec(du, CTOI(temp[0]));
        }
    }
    return t2;
}

您似乎已经为该功能添加了很多不必要的复杂性。这是一个简化的功能,适用于我的测试用例。

string divide2(string str)
{
   string ret;  // Object to be returned.
   int rem = 0; // Keep track of remainders.
   // Iterate over the characters of the input string.
   auto iter = str.begin();
   auto end = str.end();
   for ( ; iter != end; ++iter )
   {
      int n1 = CTOI(*iter);     // The number from the string.
      int n2 = creDec(rem, n1); // The number after we account for the remainder.
      int n3 = n2/2;            // Result of the division.
      rem = n2%2;               // Remainder of the division.
      if ( ret.empty() && n3 == 0 )
      {
         // Do nothing. There is no need to addd leading zeros to ret.
      }
      else
      {
         // Add the character corresponding to n3 to ret.
         ret.push_back(ITOC(n3));
      }
   }
   // If the return value is an empty string, return "0".
   if ( ret.empty() )
   {
      return "0";
   }
   else
   {
      return ret;
   }
}

工作示例。

最好还是使用范围-for循环在字符串的字符上迭代。

   for ( char ch : str )
   {
      int n1 = CTOI(ch);     // The number from the string.
       ...