Get individual digits from an Int without using strings?

99封情书 提交于 2019-12-11 14:18:46

问题


I know you can convert the Int to a string and get the digit at position x using the indexer as if it was a char array, but this conversion becomes a bit of an overhead when you're dealing with multiple large numbers.

Is there a way to retrieve a digit at position x without converting the number to a string?

EDIT:

Thank you all, I will benchmark the proposed methods and check if it is any better than converting to a string. Thread will stay unanswered for 24h in case anyone has better ideas.

EDIT 2:

After some simple tests on ulong numbers, I have concluded that converting to strings and extracting the digit can be up to 50% slower compared to the methods provided below, see approved answer.


回答1:


You could do something like this:

int ith_digit(int n, int i) {
    return (int) (n / pow(10, i)) % 10;
}

We can get the ith digit by reducing the number down to a point where that digit we want becomes in the one's place, example:

Let's say you wanted the third digit in 12345, then by reducing it to 123 (by dividing it by 10 i number of times) we can then take the remainder of that number divided by ten to get the last digit, which is the digit we wanted.



来源:https://stackoverflow.com/questions/47969434/get-individual-digits-from-an-int-without-using-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!