在Objective C中获取值最重要的数字

Seb*_*Seb 5 c math objective-c modulo

我目前在目标C中有代码可以提取整数的最高有效数字值.我唯一的问题是,如果有更好的方法,而不是我在下面提供的方式.它完成了工作,但它只是感觉像一个廉价的黑客.

代码的作用是传递一个数字并循环直到该数字已成功分为某个值.我这样做的原因是一个教育应用程序,它将数字除以它的值,并显示所有值一起添加以产生最终输出(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);
Run Code Online (Sandbox Code Playgroud)

任何建议总是非常感谢.

Ric*_*III 8

这会诀窍吗?

int sigDigit(int input)
{
    int digits =  (int) log10(input);
    return input / pow(10, digits);
}
Run Code Online (Sandbox Code Playgroud)

基本上它执行以下操作:

  1. 找出input(log10(input))中的位数并将其存储在'digits'中.
  2. input通过10 ^ digits.

您现在应该拥有最重要的数字.

编辑:如果您需要一个在特定索引处获取整数值的函数,请检查此函数:

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;
}
Run Code Online (Sandbox Code Playgroud)