zoukankan      html  css  js  c++  java
  • 编写程序交换两个数字而不使用第三个变量?

    方法1((使用算术运算符):

     

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    #include <stdio.h>

     

    int main()

    {

      int a = 10, b = 5;

      // algo to swap 'a' and 'b'

      a = a + b;  // a becomes 15

      b = a - b;  // b becomes 10

      a = a - b;  // fonally a becomes 5

      printf("After Swapping the value of: a = %d, b = %d ", a, b);

      return 0;

    }

     

    方法2(使用按位异或运算符):

     

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    #include <stdio.h>

     

    int main()

    {

      int a = 10, b = 5;

      // algo to swap 'a' and 'b'

      a = a ^ b;  // a becomes (a ^ b)

      b = a ^ b;  // b = (a ^ b ^ b), b becomes a

      a = a ^ b;  // a = (a ^ b ^ a), a becomes b

      printf("After Swapping the value of: a = %d, b = %d ", a, b);

      return 0;

    }

  • 相关阅读:
    前端请求跨域理解
    可视化交互行为
    文章标题
    在map上标记point
    基于force布局的map
    stack布局
    python一些特有语法
    histogram布局用法
    patition布局
    Shell命令行处理JSON
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007366.html
Copyright © 2011-2022 走看看