The idea is binary exponentiation. Instead of multiplying times, you square your way up. If is even, . If is odd, .
This cuts the exponent in half at each step. So becomes with one squaring, then , and so on.
For negative exponents, convert to positive: . Watch out for integer overflow when negating . Work with the absolute value carefully or use a long type.