将字符串中的bigint分为2

问题描述 投票:0回答:1

我正在编写一个函数,将String中的Big Int(128位)数字除以2.Ex: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;
}
c++ biginteger
1个回答
1
投票

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

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;
   }
}

Working example

最好还是使用range-for循环迭代字符串的字符。

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

       ...
© www.soinside.com 2019 - 2024. All rights reserved.