Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of integer power of numerical value by LeetCode

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces LeetCode how to solve the integer power problem, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Title

Realize the function double Power (double base, int exponent) and find the exponent power of base. Library functions are not allowed, and large numbers do not need to be considered.

Example 1: input: 0, 10 output: 1024.00000 example 2: input: 2.10000, 3 output: 9.26100 example 3: input: 2.00000,-2 output: 0.25000 explanation: 2-2 = 1 Universe 22 = 1 Universe 4 = 9.26100 ideas

Number1 (and operation): determine whether the rightmost bit of n binary is 1

N > > 1 (shift operation): n move one bit to the right (which can be understood as deleting the last bit)

Process:

When xreply 0: 0 is returned directly (avoid error reports for subsequent x = 1 / x operations).

Initialize res = 1

When n

< 0 时:把问题转化至 n≥0 的范围内,即执行 x = 1/x ,n = - n ; 循环计算:当 n = 0 时跳出; 当 n & 1 = 1 时:将当前 x乘入 res (即 res *= x); 执行 x = x^2(即 x *= x); 执行 n右移一位(即 n>

> = 1).

Return to res

The code class Solution {public double myPow (double x, int n) {if (x = = 0) {return 0;} long b = n; double res = 1.0; / / handles negative if (b

< 0){ x = 1/x; b = -b; } while(b >

0) {if ((b & 1) = = 1) {res * = x;} x * = x; b > > = 1;} return res }} Thank you for reading this article carefully. I hope the article "LeetCode how to solve the integer power problem of numerical values" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report