zoukankan      html  css  js  c++  java
  • 算法笔试题

    一 不引入新变量交换两个变量的值

     1  通过加法

    不好的地方在于如果a值足够大,以至于加一个数就溢出,比如int型在常见的32位或64位机器占4个字节,则最大的有符号整数是2^31-1,最小的是-2^31

    C++版本:

    #include <iostream>
    using namespace std;
     
    int main() {
        // your code goes here
        int a,b;
        a=5;
        b=8;
        a=a+b;
        b=a-b;
        a=a-b;
        cout<<"a:"<<a<<endl;
        cout<<"b:"<<b<<endl;
        return 0;
    }

    python版本:

    # your code goes here
    a=5
    b=8
    a=a+b
    b=a-b
    a=a-b
    print "a:",a,"b:",b

    2  通过减法

    C++版本:

    #include <iostream>
    using namespace std;
     
    int main() {
        // your code goes here
        int a,b;
        a=5;
        b=8;
        a=a-b;
        b=a+b;
        a=b-a;
        cout<<"a:"<<a<<endl;
        cout<<"b:"<<b<<endl;
        return 0;
    }

    python版本:

    # your code goes here
    a=5
    b=8
    a=a-b
    b=a+b
    a=b-a
    print "a:",a,"b:",b

    3 通过指针地址操作

    原理:异或运算的交换律和结合律

    C++版本:

    #include <iostream>
    using namespace std;
     
    int main() {
        // your code goes here
        int a,b;
        a=5;
        b=8;
        a=a^b;
        b=a^b;
        a=a^b;
        cout<<"a:"<<a<<endl;
        cout<<"b:"<<b<<endl;
        return 0;
    }

    python版本:  

    # your code goes here
    a=5
    b=8
    a=a^b
    b=a^b
    a=a^b
    print "a:",a,"b:",b

    3 通过异或

    原理:异或运算的交换律和结合律

    C++版本:

    #include <iostream>
    using namespace std;
     
    int main() {
        // your code goes here
        int a,b;
        a=5;
        b=8;
        a=a^b;
        b=a^b;
        a=a^b;
        cout<<"a:"<<a<<endl;
        cout<<"b:"<<b<<endl;
        return 0;
    }

    python版本:  

    # your code goes here
    a=5
    b=8
    a=a^b
    b=a^b
    a=a^b
    print "a:",a,"b:",b

  • 相关阅读:
    JavaScript中对事件简单的理解
    正则表达式 RE模块
    模块
    面向对象进阶
    元类详细解释
    四.面向对象和函数补充
    四.函数
    Python的基础知识:
    五层协议及tcp三次握手四次挥手
    nginx常见错误
  • 原文地址:https://www.cnblogs.com/xqnq2007/p/7455310.html
Copyright © 2011-2022 走看看