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

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

    Those solutions are all recursive or iterative. Might a more direct approach be a little more efficient?

    Left-to-right:

    int getDigit(int from, int index)
    {
       return (from / (int)pow(10, floor(log10(from)) - index)) % 10;
    }
    

    Right-to-left:

    int getDigit(int from, int index)
    {
       return (from / pow(10, index)) % 10;
    }
    

提交回复
热议问题