Divergent thinking ability of interview questions: how to use unconventional methods to calculate 1 + 2 + · + n

Source: Internet
Author: User

Question: 1 + 2 + · + n. It is required that keywords such as multiplication and division, for, while, if, else, switch, and case and condition judgment statements (? B: C ). Comment: This problem does not have much practical significance, because it cannot be so harsh in software development. However, many interviewers think that this is a good question that can examine the applications' divergent thinking abilities. The divergent thinking can reflect the width of their knowledge and the depth of their understanding of programming-related technologies. Analysis: There are three general ideas for finding 1 + 2 + · + n: (1) loop; (2) recursion (the if statement or condition judgment statement must be used to determine whether to continue or terminate recursion). (3) use the formula n * (n + 1)/2. These three general solutions are not feasible due to question restrictions. So how can we solve this problem with unconventional solutions? The following two solutions are provided, which correspond to four solutions. In essence, loop or recursion is adopted, but the writing method is changed. Solution 1: the basic idea of the cycle is to think about the cycle. Loop only allows the same code to be repeated for n times. We can achieve this goal without the for and while. For example, the following constructor method is used. Solution 1: Use constructor to solve a specific solution: first define a type and then create n instances of this type, then the constructor of this type will be called n times. We can put the Code related to accumulation into the constructor. Implementation Code: copy the code class Temp {public: Temp () {++ N; Sum + = N;} static void init () {N = 0; Sum = 0 ;} static unsigned int getSum () {return Sum;} private: static unsigned int N; static unsigned int Sum ;}; unsigned int Temp: N = 0; unsigned int Temp :: sum = 0; unsigned int sum_solution1 (unsigned int n) {Temp: init (); Temp * temp = new Temp [n]; delete [] temp; temp = NULL; return Temp: getSum ();} copy the code. solution 2: recursive angle basis This idea: recursive thinking. According to the limitations of the question, we cannot determine the conditions for Recursive termination in a function. Therefore, we may define two functions: a function acts as a recursive role in the original recursive function, another function is used to deal with recursive termination. What we need to do is to select one of the two functions. From the two options, we naturally think of Boolean variables. For example, when the value is true (1), we call the first function and when the value is false (0), we call the second function. Then how can we convert the value Variable n to a Boolean variable? The solution is to perform two consecutive inverse operations on n, that is !! N, so that the non-zero n is converted to true, and 0 is converted to false. There are three solutions based on this idea. Solution 2: Use virtual functions to solve specific problems: use virtual functions to select functions. For example, if the parent class virtual function processes recursive termination and the subclass class virtual function implements recursive accumulation, when n is not 0, the subclass function is called. If n is 0, the parent class function is called to complete the calculation. Implementation Code: copy the code class Base; Base * array [2]; class Base {public: virtual unsigned int sum (unsigned int n) {return 0 ;}}; class Derived: public Base {public: virtual unsigned int sum (unsigned int n) {return array [!! N]-> sum (n-1) + n ;}}; unsigned int sum_solution2 (unsigned int n) {Base B; Derived d; array [0] = & B; array [1] = & d; return array [1]-> sum (n);} copy code solution 3: Use function pointers to solve specific solutions: in a pure C programming environment, we cannot use virtual functions. At this time, we can use function pointers to simulate the code, which may be more intuitive. Implementation Code: copy the code typedef unsigned int (* fun) (unsigned int); unsigned int sum_terminator (unsigned int n) {return 0;} unsigned int sum_solution3 (unsigned int n) {fun f [2] = {sum_terminator, sum_solution3}; return f [!! N] (n-1) + n;} copy code scheme 4: Use the template type to solve the specific scheme. Finally, we can let the compiler help complete recursive computation. For example, using the template type, n is used as the template parameter. Implementation Code: copy the Code template <unsigned int n> struct sum {enum value {N = sum <n-1 >:: N + n };}; template <> struct sum <1 >{ enum value {N = 1 };}; copy the Code Description: sum <100> :: N is the result of 1 + 2 + · + 100. This method has obvious defects. Because the computation process is completed during compilation, the input n must be a constant that can be determined during compilation, that is to say, we cannot enter n dynamically. This is the biggest drawback, And the compiler has a limit on the recursive depth of recursive compilation code, that is, it requires n to be too large.

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.