Getting the most significant digit in Objective-C

I currently have code in a C object that can pull out the integer value of the most significant digit. My only question is if there is a better way to do this than with the way I cited below. It does its job, but it just looks like a cheap hack.

What the code does is that it takes a number that has passed and is passing until that number is successfully divided by a specific value. The reason I'm doing this is because it is an educational application that breaks down a number into its value and shows the values โ€‹โ€‹added together to get the final output (1234 = 1000 + 200 + 30 + 4).

int test = 1;
int result = 0;
int value = 0;

do {
    value = input / test;
    result = test;
    test = [[NSString stringWithFormat:@"%d0",test] intValue];
} while (value >= 10);

Any advice is always welcome.

+5
source share
1

?

int sigDigit(int input)
{
    int digits =  (int) log10(input);
    return input / pow(10, digits);
}

:

  • (log10(input)) .
  • input 10 ^ digits.

.

EDIT: , , :

int digitAtIndex(int input, int index)
{
    int trimmedLower = input / (pow(10, index)); // trim the lower half of the input

    int trimmedUpper = trimmedLower % 10; // trim the upper half of the input
    return trimmedUpper;
}
+8

All Articles