0

I want to implement RadixSort and get the digit of a number at a specific decimal place.

 int num (int elem, int place)
      --- if element == 12225 and place == 0
      --- expected output would be 5 (starting to count by right) 
      --- if place == 4 expected output would be 1

I wrote this method. But it's neither working nor efficient.

    static int key(int element, int decimalPlace) {
        if (element < 0)
            throw new IllegalArgumentException("invalid argument");
        int tmp = (int) (Math.log10(element) + 1);
        if (decimalPlace > tmp)
            return 0;
        else {
            return Integer.parseInt(String.valueOf(Integer.toString(element).charAt(tmp - decimalPlace)));
        }
    }

I think I should be able to solve this more efficiently

aamadmi
  • 2,680
  • 2
  • 18
  • 21
  • Perhaps simply 1) print the decimal number to a string, then 2) `String.charAt()` the digit you want? – FoggyDay Jun 10 '20 at 18:17
  • 1
    Alternatively, multiply the decimal number by 10 to the power of the place where the digit you want is (so it becomes the last digit before the decimal point), cast it to an `int` and calculate the module of the division by 10 (`% 10`) – Mario MG Jun 10 '20 at 18:20
  • Sorry, by "decimal", you mean base 10: then (if an `int`), divide by 10 to the power of the position you want and get the module of the division by 10. For example, the third position in 12345: `(12345 / 100) % 10` – Mario MG Jun 10 '20 at 18:23
  • 1
    Does this answer your question? [Get a specific digit of a number from an int in Java](https://stackoverflow.com/questions/9253716/get-a-specific-digit-of-a-number-from-an-int-in-java) – Arvind Kumar Avinash Jun 10 '20 at 18:30
  • Saying `its neither working`: What's ypur code's actual outcome for place 1 or 4 of 12225? Or what's the error you get? – hc_dev Jun 10 '20 at 19:02
  • If one of the answers solved your problem, please accept it https://stackoverflow.com/help/someone-answers# – Mario MG Jun 18 '20 at 12:01

3 Answers3

3

I would do:

return ( element / (int) Math.pow(10, decimalPlace) ) % 10
Mario MG
  • 364
  • 2
  • 13
0
class FindDecimalPosition
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(getNumber(1234567,0));
        System.out.println(getNumber(1234567,1));
        System.out.println(getNumber(1234567,2));
        System.out.println(getNumber(1234567,3));
        System.out.println(getNumber(1234567,4));
        System.out.println(getNumber(1234567,5));
        System.out.println(getNumber(1234567,6));
    }


    public static int getNumber(int num,int position){
        char [] aux = (num+"").toCharArray();

        if(position >= aux.length || position < 0 || num < 0) throw new IllegalArgumentException("invalid argument");
        return Integer.valueOf((aux[aux.length - position-1]+""));
    }
}
Lakshman
  • 469
  • 5
  • 12
  • 1
    Robust check on IllegalArguments What happens for negative inputs, e.g. `num = -1`? What for `position == aux.length` ? – hc_dev Jun 10 '20 at 19:26
0

You could solve it by two ways:

Using string operation on its decimal representation

Picking the char (digit) from decimal string representation of your positive integer:

int getDigitAtPosition(Integer integer, int zeroBasedPositionFromRight) {
  // raise error if pos < 0 or pos >= length or length == 0
  decimalRepresentation = integer.toString();
  int rightMostPosition = decimalRepresentation.length() - 1;
  int indexOfDigit = rightMostPosition - zeroBasedPositionFromRight;
  char digitChar = decimalRepresentation.charAt(indexOfDigit);

  return Integer.parseInt(digitChar);
}

Using mathematics (simple steps)

Or you can calculate it by (a) using modulo of higher power-10; then (b) subtracting lower power-10 (incl. its modulo); finally (c) divide by pos-power-10:

get pos 1 digit of 1234 = 3

becomes (a) 10^(1 +1) = 100er factor subtracted

1200 is subtracted, resulting in 34

then (b) 10^(1 -1) = 1er subtracted

4 is subtracted, resulting in 30

finally (c) integer-divide by 10^(1) (to neglect a possible remainder)

30 / 10 = 3 the desired digit's value

int getDigitAtPosition(Integer integer, int pos) {
  // raise error if pos < 0 or pos >= length or length == 0
  int higherUnit = 10^(pos +1) ; // a
  int higherPart = (integer / higherUnit) * higherUnit;
  int lowerUnit = 10^(pos -1); // b
  int lowerPart = (integer / lowerUnit) * lowerUnit;
  int posUnit = 10^(pos); // c
  int digitAtPosition = (integer - higherPart - lowerPart) / posUnit;

  return digitAtPosition;
}

Using mathematics (pow and modulo)

see related answer leveraging modular arithmetic:

More generally, the n-th digit of a number can be obtained by the formula: (number / base^(n-1)) % base

hc_dev
  • 8,389
  • 1
  • 26
  • 38