Getting a values most significant digit in Objective C

感情迁移 提交于 2019-12-07 06:43:08

问题


I currently have code in objective C that can pull out an integer's most significant digit value. My only question is if there is a better way to do it than with how I have provided below. It gets the job done, but it just feels like a cheap hack.

What the code does is that it takes a number passed in and loops through until that number has been successfully divided to a certain value. The reason I am doing this is for an educational app that splits a number up by it's value and shows the values added all together to produce 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 greatly appreciated.


回答1:


Will this do the trick?

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

Basically it does the following:

  1. Finds out the number of digits in input (log10(input)) and storing it in 'digits'.
  2. divides input by 10 ^ digits.

You should now have the most significant number in digits.

EDIT: in case you need a function that get the integer value at a specific index, check this function out:

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;
}


来源:https://stackoverflow.com/questions/9933425/getting-a-values-most-significant-digit-in-objective-c

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