Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a values most significant digit in Objective 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.

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.

like image 361
Seb Avatar asked Mar 29 '12 20:03

Seb


People also ask

How do you find most significant digits?

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.

How do you remove most significant digits from a number?

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.

What is MSB in java?

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.


1 Answers

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;
}
like image 133
Richard J. Ross III Avatar answered Sep 18 '22 09:09

Richard J. Ross III