Getting a values most significant digit in Objective C

痞子三分冷 提交于 2019-12-05 10:37:58

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