Technical interview question: F (f (n)) = =-N

Source: Internet
Author: User
Tags integer

Recently encountered a technical interview question, here to share. The title is to design a function f that makes

F (f (n)) =-N

Here n is a 32-bit integer. You cannot use imaginary or plural operations.

If you can't design a function to make it work for all integers under 32 bits, design this function so that it can be applied to as many integers as possible.

Design a function f, such that:

f (f (n)) = = N

Where n is a bit signed integer; can ' t use complex numbers a Rithmetic.

If you can ' t-design such a function for the whole range of numbers, it is for the largest range possible.

Try one:

For languages that support the built-in state of a function, such as the C language, it is easy to solve this face test. The following code can be:

C + +

int f (int n) {

static int state =-1;

State *=-1;

return n * state;

}

This defines a function built in state variable states. The first time the function f is executed, State equals 1, and the function returns N. The second time the function is executed, state equals-1, and the function returns-N. This solution can be applied to all 32-bit integers except int_min. For int_min, negation causes overflow, i.e. F (f (int_min)) = Int_min.

Of course, this topic should not be so easy to solve. How do you solve a language that doesn't support built-in state, such as C # or Java?

Try two:

You can use global variables to store the state. For example, the following C # code:

private static int state =-1;

public static int f (int i) {State

*=-1;

return state * i;

}

But this solution is still not perfect, it is not so.

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.