zoukankan      html  css  js  c++  java
  • 《Cracking the Coding Interview》——第17章:普通题——题目1

    2014-04-28 21:45

    题目:就地交换两个数,不使用额外的变量。

    解法:没说是整数,我姑且先当整数处理吧。就地交换可以用加法、乘法、异或完成,其中乘法和加法都存在溢出问题。三种方法都不能处理交换同一个数的情况,需要条件判断。

    代码:

     1 // 17.1 Do a swapping in-place.
     2 #include <cstdio>
     3 using namespace std;
     4 
     5 void swap1(int &x, int &y)
     6 {
     7     if (x == y) {
     8         return;
     9     }
    10 
    11     // what if it is double?
    12     x ^= y ^= x ^= y;
    13 }
    14 
    15 void swap2(int &x, int &y)
    16 {
    17     if (x == y) {
    18         return;
    19     }
    20 
    21     // overflow?
    22     x = x + y;
    23     y = x - y;
    24     x = x - y;
    25 }
    26 
    27 void swap3(int &x, int &y)
    28 {
    29     if (x == y) {
    30         return;
    31     }
    32     
    33     x = x ^ y;
    34     y = x ^ y;
    35     x = x ^ y;
    36 }
    37 
    38 int main()
    39 {
    40     int x, y;
    41     
    42     scanf("%d%d", &x, &y);
    43     printf("x = %d, y = %d
    ", x, y);
    44     swap1(x, y);
    45     printf("x = %d, y = %d
    ", x, y);
    46     swap2(x, y);
    47     printf("x = %d, y = %d
    ", x, y);
    48     swap3(x, y);
    49     printf("x = %d, y = %d
    ", x, y);
    50     
    51     return 0;
    52 }
  • 相关阅读:
    SMTP发邮件(直接可用)实例
    ADO.NET(二)
    ADO.NET(一)
    C# 反射(一)
    APサーバ
    DB2 相关操作
    ArrayList与LinkedList时间复杂度之对比
    java泛型问题 关于警告:XX is a raw type
    Java编程中提高性能的几点建议
    STRUTS2核心控制器:FilterDispatcher
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3698050.html
Copyright © 2011-2022 走看看