• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Pow(x, n)

早早投降了,看了这个强大的代码

 1 class Solution {
 2 public:
 3     double pow(double x, int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         bool negtive = n < 0;
 7         n = abs(n);
 8         double ret = 1.0;
 9         while (n > 0) {
10             ret = (n & 1) == 1? ret*x : ret;
11             x *= x;
12             n >>= 1;
13         }
14         return negtive? 1/ret : ret;
15     }
16 };

 C# 注意下Int32.MinValue问题就行

 1 public class Solution {
 2     public double MyPow(double x, int n) {
 3         bool neg = n < 0;
 4         bool minValue = false;
 5         if (n == Int32.MinValue) {
 6             n = Int32.MaxValue;
 7             minValue = true;
 8         }
 9         else n = Math.Abs(n);
10         double ans = 1.0;
11         double x1 = x;
12         while (n > 0) {
13             ans = (n & 1) == 1? ans * x1 : ans;
14             x1 *= x1;
15             n >>= 1;
16         }
17         if (minValue) ans *= x;
18         return neg? 1 / ans : ans;
19     }
20 }
View Code

 

posted @ 2013-04-19 15:41  ying_vincent  阅读(174)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3