zoukankan      html  css  js  c++  java
  • 给你n个数,其中有且仅有两个数出现了奇数次,其余的数都出现了偶数次。用线性时间常数空间找出出现了奇数次的那两个数

    从头到尾异或一遍,你就得到了需要求的两个数异或后的值。这两个数显然不相等,异或出来的结果不为0。我们可以据此找出两个数的二进制表达中不同的一位,然后把所有这n个数分成两类,在那一位上是0的分成一类,在那一位上是1的分到另一类。对每一类分别使用前一个问题的算法

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 void findoddnum(int a[],int n);
     4 int main()
     5 {
     6     int a[12];
     7     int i;
     8     printf("please input the arr:");
     9     for(i = 0;i < 12;i++)
    10     {
    11         scanf("%d",&a[i]);
    12     }
    13     findoddnum(a,12);
    14     system("pause");
    15     return 0;
    16 }
    17 void findoddnum(int a[],int n)
    18 {
    19     int sum = 0;
    20     int i;
    21     int j;
    22     int c = 0;
    23     int b = 0;
    24     for(i = 0;i < n;i++)
    25     {
    26         sum ^=a[i];
    27     }
    28     if(sum == 0)
    29     {
    30         printf("No such number!");
    31     }
    32     else
    33     {
    34         int count = 0;
    35         int temp = sum;
    36         int temp1 = 0;
    37         while(!(temp&1))
    38         {
    39             temp >>=1;
    40             count++;
    41         }
    42         for(j = 0;j < n;j++)
    43         {
    44             temp1 = a[j];
    45             if((temp1>>count)&1)
    46             {
    47                 c ^= temp1;
    48             }
    49         }
    50         b = sum ^ c;
    51         printf("the first number is %d",c);
    52         printf("the second number is %d",b);
    53     }
    54 }
  • 相关阅读:
    Linux 中国镜像
    VMWare 安装 Debian 9
    Linux 安装Docker compose 快速方法
    Nginx on Docker 配置
    Docker 中配置Nginx
    Nginx IPV4 问题
    VMWare中CentOS 7 配置 XShell连接
    在CentOS 7 中安装Docker
    Docker for Windows 和虚拟机VMWare共存方案
    Nginx 配置多个站点
  • 原文地址:https://www.cnblogs.com/joyclub/p/4467941.html
Copyright © 2011-2022 走看看