Java wrapper class `Integer`

provides an utility function `toOctalString(int)`

which returns an integer in octal form. However, in this post, we will also see an example on how we can convert integer to octal form mathematically without using Java API classes.

If you divide a number with 8, what you get in the reminder is the last digit of its octal form. We repeat this until dividend becomes zero, get the reminder in each iteration and mathematically append them together.

## Program:

```
package com.techstackjournal;
public class IntegerToOctal {
public static void main(String[] args) {
int num = 246;
int rem = 0, oct = 0, pwr = 0;
while (num > 0) {
rem = num % 8;
num = num / 8;
oct = oct + rem * power(10, pwr);
pwr++;
}
System.out.println(oct);
}
private static int power(int n, int p) {
int result = 1;
while (p > 0) {
result = result * n;
p--;
}
return result;
}
}
```

**Output:**

`366`

## Dry Run

Iteration | num | oct (A) | num%8 (B) | num/8 | pwr | power(10, pwr) (C) | oct A+(B*C) |
---|---|---|---|---|---|---|---|

1 | 246 | 0 | 6 | 30 | 0 | 1 | 6 |

2 | 30 | 6 | 6 | 3 | 1 | 10 | 66 |

3 | 3 | 66 | 3 | 0 | 2 | 100 | 366 |

## Leave a Reply