如何在不交换订单的情况下将多位数拆分为单独的数字

时间:2015-09-29 13:21:32

标签: c

我想将4567分成4,5,6,7, 分离的方法之一是:

int value =4567, rightDigit;
rightDigit =number%10;
number /=10;

然而结果是7,6,5,4, 如何让它打印4 5 6 7?谢谢

4 个答案:

答案 0 :(得分:3)

您无需明确存储数字。您可以使用 call stack来存储它们并按正确的顺序打印它们。

var firstAttributes = new UIStringAttributes {
    ForegroundColor = UIColor.White,
    BackgroundColor = UIColor.Black,
    Font = UIFont.FromName("Arial", 24f)
};

    var secondAttributes = new UIStringAttributes {
        ForegroundColor = UIColor.Orange,
        BackgroundColor = UIColor.Black,
        Font = UIFont.FromName("Arial", 24f)
    };


    var prettyString = new NSMutableAttributedString ("Hello 2 all of you");
    prettyString.SetAttributes (firstAttributes.Dictionary, new NSRange (0, 6));
    prettyString.SetAttributes (secondAttributes.Dictionary, new NSRange (6, 1));
    prettyString.SetAttributes (firstAttributes.Dictionary, new NSRange (7, 11));

    testlbl.AttributedText = prettyString;
    this.NavigationItem.TitleView = testlbl;

答案 1 :(得分:1)

数组或堆栈可以正常工作。你也可以使用除数(伪代码):

num = whatever
div=1'000'000'000 // ints are 2 billion max
first = false
while div > 0:
  digit = num / div
  first = first or (digit != 0)
  if first: handleDigit(digit)
  num = num % div
  div = div / 10

效率低下且不常见但应该有效。

答案 2 :(得分:1)

为此,您需要将%10操作生成的所有数字存储到数组中,然后以相反的顺序打印数组。代码为fllows -

int main()
{
    int i,c=0,value=4567,r,arr[10];
    while(value){
        r=value%10;
        arr[c++]=r;
        value/=10;
    }
    for(i=c-1;i>=0;i--){
        printf("%d",arr[i]);
    }
    return 0;
}

答案 3 :(得分:1)

通过使用堆栈,您可以解决此问题。

 #include <iostream>
  #include <stack>
    int main()
    {
        using namespace std;
        queue<int> digit;
        int number;
        cin >> number;
        while (number != 0)
        {
            digit.push(number % 10);
            number /= 10;
        }
        while (!digit.empty())
        {
            cout << digit.top() << " ";
            digit.pop();
        }
        cout << endl;
        return 0;
    }