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

前端 未结 15 1248
既然无缘
既然无缘 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:41

    simple recursion:

    #include 
    
    // 0-based index pos
    int getDigit (const long number, int pos) 
    {
        return (pos == 0) ? number % 10 : getDigit (number/10, --pos);
    }
    
    int main (void) {
        std::cout << getDigit (1234567, 4) << "\n";    
    }
    

提交回复
热议问题