首页 > 其他 > 详细

“《编程珠玑》(第2版)第2章”:A题

时间:2015-03-23 23:38:16      阅读:327      评论:0      收藏:0      [点我收藏+]

  A题是这样子的:

  给定一个最多包含40亿个随机排列的32位整数的顺序文件,找出一个不在文件中的32位整数(在文件中至少缺失一个这样的数据——为什么?)。在具有足够内存的情况下,如何解决该问题?如果有几个外部的“临时”文件可用,但是仅有几个字节的内存,又该如何解决该问题?

  位图结构

  高斯求和(与二分搜索相结合)

 

  1. 文件读写

  首先我们来看怎么进行文件的读写。有一篇博文总结的很不错,值得参考。贴出具体代码如下:

技术分享
 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <sstream>
 5 #include <math.h>
 6 using namespace std;
 7 
 8 int main()
 9 {
10     // *************************** Write File *************************** // 
11     // Open file
12     ofstream wfile("file.txt", ios::out);
13     if (!wfile)
14     {
15         cout << "The file can not be opened!" << endl;
16         exit(1);
17     }
18 
19     for (int i = 0; i < pow(2, 16); i++)
20     {
21         stringstream ss;
22         ss << i;
23         string str = ss.str();
24         wfile << str;
25         wfile << endl;
26     }
27 
28     // Close the file
29     wfile.close();
30 
31     // *************************** Read File *************************** //
32     // Open file
33     ifstream rfile("file.txt", ios::in);
34     if (!rfile)
35     {
36         cout << "The file can not be opened!" << endl;
37         exit(1);
38     }
39     
40     string line;
41     int num;
42     while (getline(rfile, line))
43     {
44         // cout << line << endl;
45         stringstream ss;
46         ss << line;
47         ss >> num;
48         cout << num << endl;
49     }
50 
51     // Close the file
52     rfile.close();
53 
54     return 0;
55 }
View Code

 

“《编程珠玑》(第2版)第2章”:A题

原文:http://www.cnblogs.com/xiehongfeng100/p/4361118.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!