[关闭]
@Lin-- 2018-10-14T16:08:14.000000Z 字数 1279 阅读 270

作业9——Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 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/22 = 1/4 = 0.25
Note:

-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−2^31, 2^31-1]

计算机数学


在此输入正文

  1. /*
  2. *File:pow.c
  3. *Author:Hongpei lin
  4. *Date:20181014
  5. *Purpose:to solve the problem in Leetcode
  6. *https://leetcode.com/problems/powx-n/description/
  7. */
  8. /**
  9. *Declaration of functions.
  10. *Input a double x and integer n
  11. *Output x^n
  12. *Method:In normal circumstances,make a circulate,let x*x execute n times
  13. *In special circumstances,make special method
  14. **/
  15. double myPow(double x, int n) {
  16. double k=1; //k memory the result
  17. //if x=1,find that x^n=1
  18. if(x==1) return 1.0;
  19. //if x=-1,and n is a even,find that x^n=1
  20. //if x=-1,and n is an odd,find that x^n=-1
  21. if(x==-1)
  22. {
  23. if(n%2==0) return 1.0;
  24. else return -1.0;
  25. }
  26. //if n=0,find that x^n=1
  27. if(n==0) return 1.0;
  28. //if n=-(2^31),find the result will overflow
  29. if(n==-2147483648) return 0.0;
  30. else if(n>0)
  31. {
  32. //the process of pow
  33. while(n!=0)
  34. {
  35. //if result is infinitely great,it will overflow
  36. if(k==NAN) return 0.0;
  37. //if n is a odd,result multiply a longly x
  38. if(n%2==1) {k*=x;}
  39. //n divide 2
  40. n=n/2;
  41. //x=x*x
  42. x*=x;
  43. }
  44. }
  45. else
  46. {
  47. //if n<0,let x=1/x,the result is (1/x)^|n|
  48. x=1/x;
  49. n=-n;
  50. while(n!=0)
  51. {
  52. //if result is infinitely small,it will overflow
  53. if(k==INFINITY) return 0.0;
  54. //the same process
  55. if(n%2==1) {k*=x;}
  56. n=n/2;
  57. x*=x;
  58. }
  59. }
  60. return k;
  61. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注