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.
The number of significant figures is determined by starting with the leftmost non-zero digit. The leftmost non-zero digit is sometimes called the most significant digit or the most significant figure. For example, in the number 0.004205, the '4' is the most significant figure.
Use the modulo operation. For example, to keep the least significant 2 digits of a decimal number num , use num % 100 . It will produce a number between 0 and 99 that is the remainder of dividing num by 100 , which is basically the least two significant digits.
The most significant bit (MSB) is the bit in a multiple-bit binary number with the largest value. This is usually the bit farthest to the left, or the bit transmitted first in a sequence. For example, in the binary number 1000, the MSB is 1, and in the binary number 0111, the MSB is 0.
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)
) and storing it in 'digits'.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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With