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

  • 相关阅读:
    基于RTP的h.264视频传输系统设计(一)
    NAS配置Time Machine,在D-Link DNS-320上的配置笔记
    重构版机房收费系统之分层、接口、数据库连接、反射+工厂(vb.net)
    复制表机构
    JVM内存
    System.gc()
    重写(Override) 重载(Overload)
    final 关键字
    JAVA stack
    java 获取环境变量
  • 原文地址:https://www.cnblogs.com/xqnq2007/p/7455310.html
Copyright © 2011-2022 走看看