Skip to main content
All Questions

Implement x to the power of n without using any built-in library.

Medium
Unlock detailed company stats for this questionUpgrade

Implement pow(x, n), which returns x raised to the power n. Don't use a built-in power function.

n can be negative, in which case x^n is 1 / x^-n. The tests round your answer to 5 decimal places before comparing.

Example 1

Input: x = 2.0, n = 10 Output: 1024.0

Example 2

Input: x = 2.0, n = -2 Output: 0.25

2^-2 is 1 / 2^2, which is 1 / 4.

Constraints

  • -100.0 < x < 100.0
  • -2^31 <= n <= 2^31 - 1
  • x isn't 0 when n is negative or 0.
  • The answer is between -10^4 and 10^4 after rounding.

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.