50. Pow(x, n)
Tags:
Medium
Skills:
Math
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu tính x^n với x là số thực và n là số nguyên (có thể âm, dương hoặc 0)
Approach - Binary exponentiation with iterative
Dựa vào biểu diễn nhị phân của n, mỗi bit 1 sẽ nhân thêm một lũy thừa tương ứng

Solution
1function myPow(x: number, n: number): number {
2 let N = n;
3 if(N < 0) {
4 x = 1 / x;
5 N = -N
6 }
7
8 let res = 1;
9 let curr_product = x;
10 while(N > 0) {
11 if(N % 2 === 1) res *= curr_product;
12 curr_product *= curr_product;
13 N = Math.floor(N / 2)
14 }
15 return res;
16};Ứng dụng vào tính lũy thừa
→ Với mỗi bit 1 trong nhị phân của n, ta sẽ nhân thêm một lũy thừa tương ứng của x
Giải thích chi tiết