zoukankan      html  css  js  c++  java
  • Fast Power

    Calculate the an % b where a, b and n are all 32bit integers.

    Analyse: divide and conquer. Be aware of overflow. 

    Runtime: 12ms

     1 class Solution {
     2 public:
     3     /*
     4      * @param a, b, n: 32bit integers
     5      * @return: An integer
     6      */
     7     int fastPower(int a, int b, int n) {
     8         // write your code here
     9         if (!a || b == 1 || n < 0) return 0;
    10         if (!n && b != 1) return 1;
    11         if (n == 1) return a % b;
    12         
    13         long temp1 = fastPower(a, b, n / 2);
    14         long temp = temp1 * temp1 % b;
    15         if (n % 2) temp *= a % b;
    16         return (int)(temp % b);
    17     }
    18 };
  • 相关阅读:
    day4
    day3
    day2
    day1
    spring-boot-note
    spring-boot-cli
    jquery ajax rest invoke
    spring-boot
    docker mysql
    jpa OneToMany
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5782538.html
Copyright © 2011-2022 走看看