How to add two numbers without using ++ or + or another arithmetic operator

后端 未结 21 2042
南笙
南笙 2020-11-27 10:48

How do I add two numbers without using ++ or + or any other arithmetic operator?

It was a question asked a long time ago in some campus interview. Anyway, today some

21条回答
  •  [愿得一人]
    2020-11-27 11:32

    If you're feeling comedic, there's always this spectacularly awful approach for adding two (relatively small) unsigned integers. No arithmetic operators anywhere in your code.

    In C#:

    static uint JokeAdder(uint a, uint b)
    {
        string result = string.Format(string.Format("{{0,{0}}}{{1,{1}}}", a, b), null, null);
        return result.Length;
    }
    

    In C, using stdio (replace snprintf with _snprintf on Microsoft compilers):

    #include 
    unsigned int JokeAdder(unsigned int a, unsigned int b)
    {
        return snprintf(NULL, 0, "%*.*s%*.*s", a, a, "", b, b, "");
    }
    

提交回复
热议问题