Evaluate a Floating Base to an Integer Power

Quick Overview

Compute a floating-point power for the full signed 32-bit exponent range, including negative exponents and zero-base constraints.

Evaluate a Floating Base to an Integer Power

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Implement `myPow(x,n)` to return the floating-point value of `x` raised to the integer exponent `n`. A negative exponent denotes the reciprocal power, and a nonzero base raised to zero is 1. ```cpp double myPow(double x, int n); ``` Return a numeric value; the decimal formatting in examples is illustrative. ### Examples ```text Input: x = 3.0, n = -3 Output: 0.037037037037... ``` ```text Input: x = -1.5, n = 4 Output: 5.0625 ``` ### Constraints - `-100.0 < x < 100.0`. - `n` is an integer from -2147483648 through 2147483647. - Either `x` is nonzero or `n > 0`; zero to a zero or negative exponent is excluded. - The mathematical result is between -10000 and 10000, inclusive.

Overview: Compute a floating-point power for the full signed 32-bit exponent range, including negative exponents and zero-base constraints.

Community answers

Answer by Coderka14

#include using namespace std; class Solution { public: double myPow(double x, int n) { long long power = n; if (power < 0) { x = 1.0 / x; power = -power; } double ans = 1.0; while (power > 0) { if (power % 2 == 1) { ans *= x; } x *= x; power /= 2; } return ans; } };
Google logo
Google
Date not reported
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Implement myPow(x,n) to return the floating-point value of x raised to the integer exponent n. A negative exponent denotes the reciprocal power, and a nonzero base raised to zero is 1.

double myPow(double x, int n);

Return a numeric value; the decimal formatting in examples is illustrative.

Examples

Input: x = 3.0, n = -3
Output: 0.037037037037...
Input: x = -1.5, n = 4
Output: 5.0625

Constraints

  • -100.0 < x < 100.0 .
  • n is an integer from -2147483648 through 2147483647.
  • Either x is nonzero or n > 0 ; zero to a zero or negative exponent is excluded.
  • The mathematical result is between -10000 and 10000, inclusive.