How to get the digits of a number without converting it to a string/ char array?

前端 未结 15 1065
既然无缘
既然无缘 2020-11-27 04:07

How do I get what the digits of a number are in C++ without converting it to strings or character arrays?

相关标签:
15条回答
  • 2020-11-27 04:49

    You want to some thing like this?

     int n = 0;
        std::cin>>n;
    
        std::deque<int> digits;
        if(n == 0)
        {
            digits.push_front(0);
            return 0;
        }
    
        n = abs(n);
        while(n > 0)
        {
            digits.push_front( n % 10);
            n = n /10;
        }
        return 0;
    
    0 讨论(0)
  • 2020-11-27 04:50

    Something like this:

    int* GetDigits(int num, int * array, int len) {
      for (int i = 0; i < len && num != 0; i++) {
        array[i] = num % 10;
        num /= 10;
      }
    }
    

    The mod 10's will get you the digits. The div 10s will advance the number.

    0 讨论(0)
  • 2020-11-27 04:50

    Use a sequence of mod 10 and div 10 operations (whatever the syntax is in C++) to assign the digits one at a time to other variables.

    In pseudocode

    lsd = number mod 10
    number = number div 10
    next lsd = number mod 10
    number = number div 10
    

    etc...

    painful! ... but no strings or character arrays.

    0 讨论(0)
  • 2020-11-27 04:51

    A simple solution would be to use the log 10 of a number. It returns the total digits of the number - 1. It could be fixed by using converting the number to an int.

    int(log10(number)) + 1
    
    0 讨论(0)
  • 2020-11-27 04:52

    Since everybody is chiming in without knowing the question.
    Here is my attempt at futility:

    #include <iostream>
    
    template<int D> int getDigit(int val)       {return getDigit<D-1>(val/10);}
    template<>      int getDigit<1>(int val)    {return val % 10;}
    
    int main()
    {
        std::cout << getDigit<5>(1234567) << "\n";
    }
    
    0 讨论(0)
  • 2020-11-27 04:55

    Not as cool as Martin York's answer, but addressing just an arbitrary a problem:

    You can print a positive integer greater than zero rather simply with recursion:

    #include <stdio.h>
    void print(int x)
    {
        if (x>0) {
            print(x/10);
            putchar(x%10 + '0');
        }
    }
    

    This will print out the least significant digit last.

    0 讨论(0)
提交回复
热议问题