获取值在目标C中的最高有效位 [英] Getting a values most significant digit in Objective C
问题描述
我目前在目标C中有代码,可以提取整数的最高有效数字值.我唯一的问题是,是否有比我下面提供的方法更好的方法.它可以完成工作,但是感觉就像是廉价的黑客一样.
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.
该代码的作用是接受一个传入的数字并循环通过,直到将该数字成功划分为某个值为止.我这样做的原因是针对一个教育性应用程序,该应用程序将其值除以一个数字,并显示所有加在一起的值以产生最终输出(1234 = 1000 + 200 + 30 + 4)
.
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.
推荐答案
这可以解决这个问题吗?
Will this do the trick?
int sigDigit(int input)
{
int digits = (int) log10(input);
return input / pow(10, digits);
}
基本上,它会执行以下操作:
Basically it does the following:
- 找出输入(
log10(input)
)中的位数并将其存储在位数"中. - 将
input
除以10 ^ digits
.
- Finds out the number of digits in input (
log10(input)
) and storing it in 'digits'. - divides
input
by10 ^ digits
.
您现在应该拥有数字中最重要的数字.
You should now have the most significant number in digits.
如果您需要一个在特定索引处获取整数值的函数,请将该函数签出:
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;
}
这篇关于获取值在目标C中的最高有效位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!