Tutorialspoint
Problem
Solution
Submissions

Power of Three

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 5

Write a Java program to determine if an integer is a power of three. An integer is a power of three if there exists an integer x such that n = 3^x.

Example 1
  • Input: n = 27
  • Output: true
  • Explanation:
    • Step 1: 27 can be expressed as 3^3.
    • Step 2: 3^3 = 3 * 3 * 3 = 27
    • Step 3: Therefore, 27 is a power of three.
Example 2
  • Input: n = 45
  • Output: false
  • Explanation:
    • Step 1: 45 cannot be expressed as 3^x for any integer x.
    • Step 2: The closest powers of three are 3^3 = 27 and 3^4 = 81.
    • Step 3: Since 45 falls between these two powers, it is not a power of three.
Constraints
  • -2^31 ≤ n ≤ 2^31 - 1
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
NumberSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Check if n is positive, as powers of three must be positive
  • Repeatedly divide n by 3 and check if the remainder is 0
  • If at any point the remainder is not 0, n is not a power of three
  • If we can divide n by 3 until we get 1, then n is a power of three
  • Alternatively, use a mathematical property: the largest power of 3 in the integer range is 3^19

Steps to solve by this approach:

 Step 1: Check if n is less than or equal to 0. If so, return false as powers of three must be positive.
 Step 2: While n is divisible by 3 (i.e., n % 3 == 0), keep dividing n by 3.
 Step 3: After the division process, if n equals 1, it means the original number was a power of three.
 Step 4: If n is not equal to 1, it means the original number was not a power of three.
 Step 5: Return true if n equals 1, false otherwise.

Submitted Code :