Question

Let's say I have a number like 134658 and I want the 3rd digit (hundreds place) which is "6".

What's the shortest length code to get it in Objective-C?

This is my current code:

int theNumber = 204398234;
int theDigitPlace = 3;//hundreds place
int theDigit = (int)floorf((float)((10)*((((float)theNumber)/(pow(10, theDigitPlace)))-(floorf(((float)theNumber)/(pow(10, theDigitPlace)))))));

//Returns "2"
Était-ce utile?

La solution

There are probably better solutions, but this one is slightly shorter:

int theNumber = 204398234;
int theDigitPlace = 3;//hundreds place
int theDigit = (theNumber/(int)(pow(10, theDigitPlace - 1))) % 10;

In your case, it divides the number by 100 to get 2043982 and then "extracts" the last decimal digit with the "remainder operator" %.

Remark: The solution assumes that the result of pow(10, theDigitPlace - 1) is exact. This works because double has about 16 significant decimal digits and int on iOS is a 32-bit number and has at most 10 decimal digits.

Autres conseils

How about good old C?

int theNumber = 204398234;
char output[20];   //Create a string bigger than any number we might get.
sprintf(output, "%d", theNumber);
int theDigit = output[strlen(output)-4]-'0'; //index is zero-based.

That's really only 2 executable lines.

Yours is only 1 line, but that's a nasty, hard-to-understand expression you've got there, and uses very slow transcendental math.

Note: Fixed to take the 3rd digit from the right instead of the 3rd from the left. (Thanks @Maddy for catching my mistake)

Another solution that uses integer math, and a single line of code:

int theNumber = 204398234;
int result = (theNumber/100) % 10;

This is likely the fastest solution proposed yet.

It shifts the hundreds place down into the 1s place, then uses modulo arithmetic to get rid of everything but the lowest-order decimal digit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top