Results 1 to 2 of 2

Thread: Problem regarding FUNCTION

  1. #1
    Junior Member
    Join Date
    Jan 2008
    Answers
    3

    Problem regarding FUNCTION

    Help solve a problem regarding FUNCTION

    What the followng function is doing:

    string f(const string &x) {
    return x.empty()? x : f(x.substr(1)) + x[0];
    }


    Guys - Please help solve this problem. Appreciate it.


  2. #2
    Contributing Member
    Join Date
    Sep 2006
    Answers
    42

    Re: Problem regarding FUNCTION

    Hi Heidi,
    This is my analysis:

    Take the string HEIDI.

    The first time the function will be called with
    f("HEIDI")
    return x.empty()? x : f(x.substr(1)) + x[0];
    Now the x.empty() will return false. So the control will call the function again as such f("EIDI").
    The above statement can be read as:
    return f("EIDI") + "H"
    The next time it is called the statement becomes
    return f("IDI") + "E"
    and so on....


    Esentially, this function will reverse the string passed to it.

    Assumptions: The substring method returns the substring from the index to the end of the string.

    Regards,
    Sahil.

    --Smile, it makes people wonder what you are thinking.



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
About us
Applying for a job can be a stressful and frustrating experience, especially for someone who has never done it before. Considering that you are competing for the position with a at least a dozen other applicants, it is imperative that you thoroughly prepare for the job interview, in order to stand a good chance of getting hired. That's where GeekInterview can help.
Interact