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

  • 相关阅读:
    Servlet的数据库访问
    Servlet 网页重定向
    Intellij idea创建javaWeb以及Servlet简单实现
    Tomcat
    QQ简易版
    单例
    centos7 jdk安装
    centos7 allure安装
    centos中执行apt-get命令提示apt-get command not found
    centos mysql使用踩过的坑
  • 原文地址:https://www.cnblogs.com/xqnq2007/p/7455310.html
Copyright © 2011-2022 走看看