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 numbers at the same time.

1, self-thought very easy solution:

Because there is no need to consider the problem of large numbers. The problem looks very easy. Many candidates will be able to write code such as the following 30 seconds after they see the title:

Public double powerwithexponent (double base,int exponent) {Double result = 1.0;for (int i = 1;i<= exponent;i++) {result = Result*base;} return result;}
Yes, 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 completely out of consideration and contains only a positive exponent.

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. Then count the results of the second side and then take the countdown. Since there is a reciprocal, it is very natural for us to think that there is no possibility of the 0 to the reciprocal, assuming that the countdown to 0 what to do? When base bases are 0 and the exponent is negative, we do not do special processing, and we find that the countdown to 0 results in a program execution error. How do you tell the caller of the function that there was such an error? Can throw exceptions in Java to resolve.

The last point to be pointed out is that 0 of the 0-time Square is mathematically meaningless. So either the output 0 or the 1 are capable of receiving. But it all needs to be clear to the interviewer that we've taken this boundary value into account.

With these relatively comprehensive and very many considerations in place, we are able to change the original code such as the following:

/** * Title: Implement function Double Power (double base,int exponent), seek base exponent. Library functions must not be used at the same time do not need to consider the large number of problems * for this problem, consider 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 Clas s E11power {public double power (double base,int exponent) throws exception{double result = 0.0;if (equal (base,0.0) &&am P exponent<0) {throw new Exception ("0 has a negative power of no meaning");} 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;} Infer two double type data, computer has 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));}}
Because computers represent decimals (including float and double decimals) there is an error. We cannot infer whether two decimals are equal directly with the equals sign (= =). Assuming that the absolute value of the difference between the two decimals is very small, for example, less than 0.0000001, you can think they are equal.

At this point we have been very thoughtful, we can get a lot of interviewer's request.

But suppose that the interviewer we meet is a person who pursues perfection in efficiency, then he may remind us that the function powerwithexponent has a quicker way.

3, comprehensive and efficient solution. Make sure we get an offer.

Assuming that 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 a number 32 times. Suppose we had known it 16 times. Then just 16 times on the basis of the square once again can be.

and 16 times the square is 8 square. And so on. We ask 32 times to have only 5 powers: square first. On the basis of the square to seek 4, on the basis of 4 times to seek 8, on the basis of 8 times to seek 16. Finally, on the basis of 16 this party to seek 32.

That is to say, we can use the following to find the n-th side of a:



This formula is when we use O (logn) time to find the Fibonacci sequence. The formula discussed. This formula is very easy to implement with recursion.

The new powerwithexponent code such as the following:

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, substituting the bitwise AND operator for the remainder operator (%) to infer whether a number is odd or even. The efficiency of bit operation is much higher than that of multiplication method and the calculation of redundancy.

Now that we're optimizing the code, we're going to optimize it.

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

Related Article

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.