Skip to content
ExamSpine

Lesson 4.5 · Write it

Integer power

A functionPython or Java7 tests, 4 of them hidden

On a phone? Put the lines in order instead

Write a function that returns base raised to the power exponent, using a loop, not a built-in power function.

  1. base and exponent are whole numbers, chosen so that the answer is from -1000000000 to 1000000000, and exponent is at most 100.
  2. exponent is always 0 or positive.
  3. Anything raised to the power 0 is 1.
  4. Do not use ** (Python) or Math.pow (Java).

Only the number your function returns is checked.

def int_power(base: int, exponent: int) -> int

You cannot use these in this question:

  • pow()
  • .__pow__()
  • import math
  • import cmath

This question is about writing the loop yourself, so built-in power functions are not allowed.

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • int_power(2, 3) should return 8: 2 cubed is 8 (rule 1)
  • int_power(5, 0) should return 1: anything to the power 0 is 1 (rule 3)
  • int_power(3, 2) should return 9: 3 squared is 9 (rule 1)

public static int intPower(int base, int exponent)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Math.pow()

This question is about writing the loop yourself, so built-in power functions are not allowed.

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • intPower(2, 3) should return 8: 2 cubed is 8 (rule 1)
  • intPower(5, 0) should return 1: anything to the power 0 is 1 (rule 3)
  • intPower(3, 2) should return 9: 3 squared is 9 (rule 1)
solution.pySolution.java