# Determine if Number is a Power of Three in Java

## The challenge

Given an integer `n`, return `true` if it is a power of three. Otherwise, return `false`.

An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`.

Example 1:

```Input: n = 27
Output: true```

Example 2:

```Input: n = 0
Output: false```

Example 3:

```Input: n = 9
Output: true```

Example 4:

```Input: n = 45
Output: false```

Constraints:

• `-231 <= n <= 231 - 1`

## The solution in Java code

Using `Math.log(n)` divided by `Math.log(3)` we can get a `double` back which when rounded using `Math.round` will result in a `3` being returned if the input number is a power of 3.

We can then compare the power of that to the input value to return a resultant `boolean`.

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```class Solution {
public boolean isPowerOfThree(int n) {
// catch the edge case
if (n==0) return false;

// use the built in Maths utils
return n == Math.pow(3, Math.round(Math.log(n)/Math.log(3)));

}
}
```Code language: Java (java)```
Tags:
Subscribe
Notify of