The sword refers to the offer surface question one (Java Edition): the integer number of values of the square

Source: Internet
Author: User

Title: Implements the function double Power (double base,int exponent), seeking the exponent of the base. Do not use library functions and do not need to consider large number problems

1, self-thought very simple solution:

Since there is no need to consider the question of large numbers, the problem seems simple, and many candidates can write the following code after 30 seconds of reading the topic:

Public double powerwithexponent (double base,int exponent) {Double result = 1.0;for (int i = 1;i<= exponent;i++) {result = Result*base;} return result;}
Well, unfortunately, writing fast does not necessarily get the interviewer's favor, because the interviewer will ask the input index (exponent) less than 1 is 0 and negative when what to do? The above code is not considered at all, only the case of positive exponent is included.

2, comprehensive but not efficient solution, we are not far from the offer

We know that when the exponent is negative, we can first calculate the absolute value of the exponent, and then calculate the result of the second side and then take the reciprocal. Since there is a reciprocal, it is natural to think that there is no possibility of the 0 to the reciprocal, if the 0 for the countdown to do? When base bases are 0 and the exponent is negative, we do not do special processing, we will find the countdown to 0 to cause the program to run an error. How do you tell the caller of the function that this error has occurred? Exceptions can be thrown in Java to resolve.

Finally, it should be pointed out that since 0 of the 0 are mathematically meaningless, so whether the output 0 or 1 are acceptable, but this needs to be clear with the interviewer, indicating that we have taken into account the boundary value.

With these relatively comprehensive considerations in mind, we can modify the original code as follows:

/** * Title: Implement function Double Power (double base,int exponent), seek base exponent. Do not use library functions, and do not need to consider the large number of problems * for this problem, there are four cases: * 1, base 0, the exponent is negative, meaningless * 2, the exponent is 0, return 1 * 3, the exponent is negative, return 1.0/base,-exponent * 4, exponential positive, base, Exponent */package swordforoffer;/** * @author Jinshuangqi * * July 30, 2015 */public class E11power {public double power (dou ble base,int exponent) throws exception{double result = 0.0;if (equal (base,0.0) && exponent<0) {throw new Except Ion ("negative power of 0 is meaningless");} if (equal (exponent,0)) {return 1.0;} if (exponent <0) {result= powerwithexponent (1.0/base,-exponent);} Else{result = Powerwithexponent (base,exponent);} return result;}  Private double powerwithexponent (double base,int exponent) {Double result = 1.0;for (int i = 1;i<= exponent;i++) {result = Result*base;} return result;} Judging two double type data, the computer has the error private Boolean equal (double num1,double num2) {if (num1-num2>-0.0000001) && ( num1-num2<0.0000001)) {return true;} Else{return false;}} public static void Main (string[] args) throws Exception{e11power test= new E11power (); System.out.println (Test.power (3,-1));}}
Since computers represent decimals (including float and double decimals) there is an error, we cannot directly use the equals sign (= =) to determine whether two decimals are equal. If the absolute value of the difference between the two decimals is small, such as less than 0.0000001, they can be considered equal.

At this point we have been very thoughtful, we have been able to get a lot of interviewer's request. But if the interviewer we meet is a person who pursues perfection in efficiency, then he may remind us that the function powerwithexponent there is a quicker way.

3. Comprehensive and efficient solution to ensure we get an offer

If the input exponent exponent is 32, we need to do 31 powers in the loop of the function powerwithexponent. But we can think of another way of thinking: Our goal is to find out a number of 32 times, if we already know its 16 square, then as long as 16 times put on the basis of the square once on it. and 16 times the square is 8 square. So and so on, we ask for 32 times only need 5 times of the powers: first squared, on the basis of the square of 4, on the basis of 4 to seek 8 square, on the basis of 8 to seek 16, and finally on the basis of 16 on the side of 32.

That means we can use the following to find the n-th side of a:



This formula is the formula that we discussed when we first used O (LOGN) time to find the Fibonacci sequence, and this formula can be easily implemented by recursion. The new Powerwithexponent code is as follows:

Private double PowerWithExponent2 (double base,int exponent) {if (exponent = = 0) return 1;if (exponent = 1) return base; Double result = PowerWithExponent2 (base,exponent >>1); result *= result;if ((exponent&0x1) = = 1) result *=base; return result;}
Finally, one more detail: we use the right-shift operation instead of 2 to determine whether a number is odd or even by substituting the bitwise AND operator for the remainder operator (%). The efficiency of bit operation is much higher than that of multiplication method and redundancy operation. Now that we're optimizing the code, we're going to optimize it.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The sword refers to the offer surface question one (Java Edition): the integer number of values of the square

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.