Flare Cat - 8 months ago 32

Java Question

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

`boolean`

`double`

`int`

`length(int)`

`power(double base, int exponent)`

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!

Answer

Here is some pseudocode:

```
int findDigit(int num, int n) {
for (i = 0; i < n-1; i++) {
num = num / 10;
}
return num % 10;
}
```