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

  • 相关阅读:
    ajax的原理及实现方式
    在linux中添加环境变量
    ftp简单命令
    linux命令之scp
    java中创建对象的方法
    10个调试技巧
    java读取.properties配置文件的几种方法
    Java对象和XML转换
    Java Float类型 减法运算时精度丢失问题
    Java内存分配全面浅析
  • 原文地址:https://www.cnblogs.com/xqnq2007/p/7455310.html
Copyright © 2011-2022 走看看