gpt4 book ai didi

objective-c - 在 Objective C 中获取值的最高有效位

转载 作者:太空狗 更新时间:2023-10-30 03:50:10 26 4
gpt4 key购买 nike

我目前在 Objective-C 中有代码可以提取整数的最高有效数字值。我唯一的问题是,是否有比我在下面提供的方法更好的方法。它完成了工作,但感觉就像一个廉价的 hack。

代码所做的是,它接受一个传入的数字并循环遍历,直到该数字被成功除以某个值。我这样做的原因是为了一个教育应用程序,它根据它的值拆分一个数字,并显示所有加在一起的值以产生最终输出 (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);

任何建议总是非常感谢。

最佳答案

这会成功吗?

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

基本上它做了以下事情:

  1. 找出输入中的位数 (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;
}

关于objective-c - 在 Objective C 中获取值的最高有效位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9933425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com