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

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

    What about floor(log(number))+1?

    With n digits and using base b you can express any number up to pow(b,n)-1. So to get the number of digits of a number x in base b you can use the inverse function of exponentiation: base-b logarithm. To deal with non-integer results you can use the floor()+1 trick.

    PS: This works for integers, not for numbers with decimals (in that case you should know what's the precision of the type you are using).

提交回复
热议问题