Flare Cat Flare Cat - 4 months ago 12
Java Question

How to put the digits of a number into an integer array?

In my AP computer science class, we are working on an algorithm assignment. We may only use the data types

, and
. We can not use any of Javas classes for data types or their math library (in other words, we have to build everything from the ground up). I already have working methods that determine the amount of digits a given integer has (
), and one that calculates power (
power(double base, int exponent)
). I believe those will be needed for the one algorithm I'm stuck on. The algorithms description is listed below:

Write a method findDigit (int num, int n) that returns the nth digit from the right of a given
integer where n is a positive integer. For example,
findDigit (30568,2) will return 6,
findDigit(234,5) will return 0,
findDigit(-4532,3) will return 5

I was going to use the string class until I realised I wasn't allowed to. This has to be done using only math operations. If one of you could give me the logic on how to make an array that contains the digits of an integer, I'll be good to go from there. I would prefer logic over code (so I can get practice writing it), but code in either c++ or java is fine as well.

I had some code that I thought would work, but ended up not working. I can provide it if you would like to look at it if needed.

Thanks in advance!


Here is some pseudocode:

int findDigit(int num, int n) {

  for (i = 0; i < n-1; i++) {
    num = num / 10;

  return num % 10;