【问题标题】:separate digits of a long number in c++c ++中长数字的单独数字
【发布时间】:2010-12-02 23:23:28
【问题描述】:

例如,我有长号码 12345678901,我想分别获取每个数字以使用它。我真的很努力,但我没有做到这一点?有什么想法吗?

但我对所有这些都有问题 当我尝试使用 11 位或更多位数(我想要的)的程序时,我的程序停止工作 我在 Visual Studio 中运行我的程序 在其他情况下 - 较小的数字 - 很好.. 与我的号码长这一事实有什么联系吗?

【问题讨论】:

标签: c++ long-integer digits


【解决方案1】:
std::vector<int> digits;

while(number > 0)
{
   digits.push_back(number%10); //push the last digit in
   number /= 10; //truncate the digit
}

std::reverse(digits.begin(), digits.end()); // the digits were in reverse order

【讨论】:

    【解决方案2】:

    这将为您提供变量 b 中的数字。

    long a = 12345678901;
    while(a > 0) {
       long b = a % 10;
       a /= 10;
    }
    

    【讨论】:

      【解决方案3】:

      一种方法是将数字转换为字符串(不确定该方法是什么,但我知道存在这样的东西),然后一次访问字符串的每个字符。

      【讨论】:

      • 你可以用 itoa 函数做到这一点
      • sprintf(myString, "%d", myNumber);
      • 哎呀 :) 为什么不只是boost::lexical_cast&lt;std::string&gt;(myNumber)?我认为lexical_cast 可能正在成为 C++0x 中标准库的一部分(我需要检查一下),这使得这种方法更加容易。
      • 假设我使用返回 char* 的 itoa。例如,我如何使用第三位数字?
      • 我如何使用词法转换?用你写的那一行 sgolodetz?
      【解决方案4】:
      long residual= number;
      int base= 10;
      
      do
      {
          long digit= residual%base;
          std::cout << digit << '\n';
          residual/= base;
      } while (residual!=0);
      

      【讨论】:

        【解决方案5】:

        不用计算数字,你可以通过将其转换为字符串来得到你想要的:

        // This converts the binary representation of the long into a string.
        std::stringstream ss;
        ss << long_number;
        std::string number_as_string = ss.str();
        
        // Then visit all the characters of the string.
        for (std::string::const_iterator it = number_as_string.begin();
             it != number_as_string.end();
             ++it)
        {
            std::cout << *it << std::endl;
        }
        

        这将打印数字,例如,如果您有 12345:

        1
        2
        3
        4
        5
        

        所以你可以像上面的代码一样处理访问迭代器*it的每一个。

        【讨论】:

          猜你喜欢
          • 2011-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多