Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

💯程序设计

简答题
引用&的用法(23)
作为函数的形参表示,可以在函数调用传参时直接操纵引用的变量,并保持这种改
变。
作为单目运算符取地址,其值可以作为地址赋给指针变量。
作为双目运算符做与运算。
解释对象和变量的作用范围和生存周期(22)
对象
对象是类的一个实例,类的内部成员有变量和函数,根据不同的作用域关键字拥
有不同的作用范围。对于public变量可以直接被对象调用,protected和private
则不可以。其生存周期由其所处的环境决定,如果是定义在栈上则会随着函数调
用的完成而自动析构,如果定义在堆上则需要程序员手动释放。
变量

程序设计 1
变量的作用域分为全局变量,可以被整个文件访问到;局部变量,仅仅被这个函
数或者结构体内部可以访问。其生存周期也遵守堆栈的特性。
在、
static C C++ java 、 内的使用场景和作用。(18)
static in C

static全局变量
都是存储在.data段或者.bss段,但它只在定义它的源文件内有效,其它源文
件无法访问。
static局部变量

静态局部变量被编译器放在全局存储区.data,虽然是局部的,但是在程序的
整个生命周期中存在
静态局部变量只能被其作用域内的变量或函数访问
静态局部变量如果没有被用户初始化,则会被编译器自动赋值为0,以后每次
调用静态局部变量的时候都用上次调用后的值
static函数

只能在当前文件内部调用
static in C++

在 C++ 中,全局变量的使用方法类似于 C,只是在 C++ 的标准中,不建议使用


static 全局变量这种方式,而是使用 unnamed namespace。

static in JAVA
Java 中的 static 不改变成员的访问权限,且不允许用来修饰局部变量。
static 变量

静态变量被所有的对象所共享,在内存中只有一个副本,当且仅当在类初次
加载时被初始化。
static block

块可以置于类的任何地方,类中可以有多个static块。在类初次被加载
static
的时候,会按照static块的顺序来执行每个static块,并且只执行一次。
static import

程序设计 2
通过在 import 之后使用关键字 static,可以导入类或接口的静态成员,这称
为静态导入。使用静态导入可以直接通过名称来引用静态成员,而不必使用
类名来进行限定,这简化并缩短了使用静态成员所需的语法。但请不要过度
使用。
多态性在C++、Java内都有哪些体现,两种语言任选一种作答。(18)
静态多态(函数重载多态) 动态多态(虚函数多态)
编译器在编译时,根据函数或模 在运行时确定调用哪个函数的版
板的参数类型进行静态绑定(静 本。通过基类指针或引用调用虚
态解析),决定使用哪个函数或 函数,根据指针或引用指向的实
模板,因此效率较高 际对象的类型,决定调用哪个派
生类的方法。
#include <iostream>
#include <iostream>
class Calculator {
public: class Shape {
int add(int a, int b) { public:
return a + b; virtual void draw() {
} std::cout << "Drawi
}
double add(double a, do };
return a + b;
} class Rectangle : public Sh
}; public:
void draw() override {
int main() { std::cout << "Drawi
Calculator calculator; }
};
int sum1 = calculator.a
double sum2 = calculato class Circle : public Shape
public:
std::cout << "Sum1: " < void draw() override {
std::cout << "Sum2: " < std::cout << "Drawi
}
};

程序设计 3
return 0;
} int main() {
Shape* shapePtr;

Rectangle rectangle;
Circle circle;

shapePtr = &rectangle;
shapePtr->draw(); // 输
shapePtr = &circle;
shapePtr->draw(); // 输
return 0;
}


define typedef 的区别(14)
执行阶段不同
关键字 typedef 在编译阶段有效, typedef 有类型检查的功能
#define 则是宏定义,发生在预处理阶段,它只进行简单而机械的字符串替换,
而不进行任何检查
功能不同
typedef 用来定义类型的别名,并且可以跨平台使用

#define 不只是可以为类型取别名,还可以定义常量、变量、编译开关等

作用域不同
typedef在类内的定义默认为private,其他类或者非成员函数无法访问

#define 没有作用域的限制,只要是之前预定义过的宏,在以后的程序中都可以
使用
int 变量和int* 变量的区别(14)
int a 定义的是4字节的空间,将会分配32位用于存储一个整型变量。

程序设计 4
是指针变量,指针也是变量,所有的变量都会有一个地址来保存他的值。指针
int*a
的大小根据不同的系统不一样,但是都是占一个int型,如果是32位,就是4个字节。
成员函数和非成员函数的区别(20)
成员函数是指属于某个类的函数,它们可以访问类的私有成员和保护成员。成员函数用于
对类的对象进行操作,而非成员函数则不需要有对象存在就可以被调用。
访问权限不同
成员函数是指属于某个类的函数,它们可以访问类的私有成员和保护成员
非成员函数只能访问类的public成员
函数调用方式不同
成员函数需要通过类的对象来进行调用
而非成员函数可以直接调用
多态性不同
成员函数可以有多个同名函数,只要它们的参数列表不同
而非成员函数不行
重载性不同
成员函数可以重载运算符
非成员函数则不一定能够重载运算符
算法题
快速排序(23)
int partition(int arr[],int low,int high)
{
int pivot = arr[low];
while(low<high)
{
while(arr[high]>pivot&&low<high)high--;
arr[low] = arr[high];
while(arr[low]<pivot&&low<high)low++;

程序设计 5
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}

void quicksort(int arr[],int low,int high)


{
if(low<high)
{
int mid = partition(arr,low,high);
quicksort(arr,low,mid-1);
quicksort(arr,mid+1,high);
}
return;
}

二维平面找顶峰点(23)
// 二分查找二维矩阵里的最大值
pair<int,int> findtop(vector<vector<int>> matrix)
{
int m = matrix.size();
int n = matrix[0].size();
int l = 0;
int r = m-2;
while(l<=r)
{
int mid = (l+r)/2;
int index = indexOfMax(matrix[mid]);
if(matrix[mid][index]<matrix[mid+1][index])
l = mid+1;
else
r = mid-1;
}

程序设计 6
return pair{l,indexOfMax(matrix[l])};
}

加法拆分递归非递归(23)
// 非递归写法 // 递归写法
vector<string> res; vector<string> res;
void DivideIterate(int sum) void DivideRecurtion(int remai
{ {
stack<int> curdata; if(remain==0)
stack<vector<int>> path; {
stack<int> remain; string p;
for(auto x:path)
int start = 0; p = p+"->"+to_string(x
while(!path.empty()||start res.push_back(p);
{ return;
if(path.empty()) }
{ else if(remain>=start)
start++; {
curdata.push(start for(int i=start,i<=rem
vector<int> p; {
p.push_back(start path.push_back(i)
path.push(p); DivideRecurtion(re
remain.push(sum-st path.pop_back();
} }
else }
{ else
int data = curdata return;
curdata.pop(); }
vector<int> p = pa
path.pop();
int r = remain.top
remain.pop();
if(r==0)
{

程序设计 7
string res_p;
for(auto x:p)
res_p = res_p+
res.push_back
}
else if(r>=data)
{
for(int i=data
{
curdata.pu
p.push_bac
remain.pus
}
}
}
}
return;
}

三数之和
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
int n = nums.size();
for(int i = 0;i<n;i++)
{
if(nums[i]>0)
return res;
if(i>0&&nums[i]==nums[i-1])
{continue;}
int l = i+1;
int r = n-1;
while(l<r)
{

程序设计 8
if(nums[i]+nums[l]+nums[r]>0)
r--;
else if(nums[i]+nums[l]+nums[r]<0)
l++;
else
{
res.push_back(vector<int>{nums[i],nums[l],nums[r

while(l<r&&nums[l]==nums[l+1])
l++;
while(l<r&&nums[r]==nums[r-1])
r--;

l++;
r--;
}
}
}
return res;
}

中间数的定义为:数列中小于这个数的元素的数量,等于大于这个数的
元素的数量。 如 2 3 5 5 6 7,则5 为中间数,输出为:5 5(两个5);
若没有中间数,如 1 2 3 4,则输出:-1.(18)
void findmid(vector<int> arr)
{
sort(arr.begin(),arr.end());
int index = 0;
int flag = false;
while(index!=arr.size())
{
int left = index;
int right = index;
while(right!=arr.size()&&arr[right]==arr[left])

程序设计 9
right++;
int count_left = left;
int count_right = arr.size()-right-1;
if(count_left==count_right)
{
while(right-left!=0)
cout<<arr[left]<<' ';
flag = true;
break;
}
}
if(!flag)
cout<<-1<<endl;
return;
}

找k平衡点(19)
vector<int> findkequal(vector<int> arr,int k)
{
vector<int> res;
vector<int> presum;
int sum = 0;
for(auto x:arr)
{
sum+=x;
presum.push_back(sum);
}
for(int i = k;i<=arr.size()-k-1;i++)
{
int l = i-k;
int r = i+k;
l = presum[i]-presum[l];
r = presum[r]-presum[i];
if(l==r)

程序设计 10
res.push_back(i);
}
return res;
}

非递归、递归求二叉树度为k的节点数量(18)
// 非递归后序遍历 // 递归,后序遍历,学一下
vector<int> res(3); vector<int> res(3);
void IterateBackOrder(TreeNode void BackOrder(TreeNode* root
{ {
stack<TreeNode*> TreeST; int count = 0;
TreeST.push(root); if(root->left!=NULL)
while(!TreeST.empty()) {BackOrder(root->left);cou
{ if(root->right!=NULL)
TreeNode* node = TreeS {BackOrder(root->right);co
TreeST.pop(); res[count]++;
int count = 0; return;
if(node->left=!=NULL) }
count++;
if(node->right!=NULL)
count++;
res[count]++;
if(node->left)
{TreeST.push(node->lef
if(node->right)
{TreeST.push(node->rig
return;
}
}

求出一个数组中有多少对相加等于2016 的数(16)

程序设计 11
思路:哈希,复杂度O(nlogn)
vector<pair<int,int>> findsum2016(vector<int> arr)
{
map<int> mp;
vector<pair<int,int>> res;
for(auto x:arr)//o(n)
mp[x]++;
for(auto x:arr)//n
{
if(x*2==2016&&mp[x]==2)
{
mp[x]-=2;
res.push_back({x,x});
}
else
if(mp[2016-x]!=0)//logn
{
mp[2016-x]--;
mp[x]--;
res.push_back({x,2016-x});
}
}
return res;
}

线性表逆转,用链表存储,递归与非递归方法实现(13)
void reverse(ListNode* &head)/ ListNode* top;// 递归
{ ListNode* reverse(ListNode* he
ListNode* cur = head; {
ListNode* pre = NULL; if(head==NULL)
while(cur!=NULL) return NULL;
{ if(head->next==NULL)
ListNode* tmp = cur->n {

程序设计 12
cur->next = pre; top = head;
pre = cur; return head;
cur = tmp; }
} else
return; {
} ListNode nxt = reverse
nxt->next = head;
return head;
}
}

两个有序链表合并,递归与非递归
ListNode* mergeTwoLists(ListNo ListNode* mergeTwoLists(ListNo
if(p1==NULL) {// 递归
return p2; if(list1==NULL&&list2!=NULL
if(p2==NULL) return list2;
return p1; if(list1!=NULL&&list2==NULL
ListNode* preHead = new Li return list1;
ListNode* pre = preHead; if(list1==NULL&&list2==NULL
while(p1!=NULL&&p2!=NULL) return NULL;
{ else
if(p1->val<p2->val) {
{ if(list1->val<list2->val
pre->next = p1; {
p1 = p1->next; list1->next = mergeT
} return list1;
else }
{ else
pre->next = p2; {
p2 = p2->next; list2->next = mergeT
} return list2;
pre = pre->next; }
} }
if(p1!=NULL)

程序设计 13
pre->next = p1;
else
pre->next = p2;
return preHead->next;
}

递归非递归实现:二叉搜索树第k大的元素值
vector<int> res; // 中序遍历,找下标为 的元素即可
k-1
void midOrder(TreeNode* root,i vector<int> res;
{// 非递归中序遍历 void midOrder(TreeNode* root,i
stack<TreeNode*> TreeST; {// 递归中序遍历
TreeNode* cur = root; if(res.size()==k)
while(cur!=NULL||!TreeST.e return;
{ else
if(cur!=NULL) {
{ if(root==NULL)
TreeST.push(cur); return;
cur = cur->left; else
} {
else midOrder(root
{ res.push_back
cur = TreeST.top( midOrder(root
TreeST.pop(); return;
res.push_back(node }
if(res.size()==k) }
return; }
cur = cur->right;
}
}
}

判断一棵树是否为二叉搜索树

程序设计 14
TreeNode* pre=NULL;
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
bool left = isValidBST(root->left);
if(pre!=NULL&&pre->val>=root->val)
return false;

pre = root;

bool right = isValidBST(root->right);


if(left&&right)
return true;
else
return false;
}

求二叉树的高和最长路径,递归非递归(17)
int maxheight = 0; //复习一下层次遍历
string p; void FindHeightAndPath(TreeNod
void FindHeightAndPath(TreeNod {
{ int height = 0;
if(root->left==NULL&&root queue<TreeNode*> qqTree;
{ queue<vector<int>> qqPath
path.push_back(root->v qqTree.push(root);
if(path.size()>maxheig while(!qqTree.empty())
{ {
maxheight = path.s TreeNode* node = qqTre
string res = ""; vector<int> curpath =
for(auto x:path) qqTree.pop();
{res = res+"->"+to qqPath.pop();
p = res; if(node->left==NULL&&n
return; {

程序设计 15
} curpath.push_back
} if(height<curpath
else {
if(root->right) height = curpa
{ path = curpath
path.push_back(roo }
FindHeightAndPath }
path.pop_back(); if(node->left)
} {
else qqTree.push(node->
if(root->left) qqPath.push(curpat
{ }
path.push_back(roo if(node->right)
FindHeightAndPath {
path.pop_back(); qqTree.push(node->
} qqPath.push(curpat
return; }
} }
}

输入一个二位数组,内容是。#*
,输出一共有多少个组成的邻居
######*##*

团体以及最大的一个邻居团体有
多少个*(*的相邻的8个位置都算
###*##****#

是他的邻居),格式大概如右
(18)
####***#**#

#****##***#

int dx[4] = {0,0,1,-1};


int dy[4] = {1,-1,0,0};
int BFS(int x,int y,vector<vector<char>>& matrix)
{
int m = matrix.size();
int n = matrix[0].size();

程序设计 16
int count = 0;
queue<pair<int,int>> qq;
qq.push({x,y});
count++;
matrix[x][y] = '#';
while(!qq.empty())
{
auto [x,y] = qq.front();
qq.pop();
for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++)
{
if(x+i<m&&0<=x+i&&y+j<n&&0<=y+j&&matrix[x+i][y+j]=='
{qq.push({x+i,y+j});count++;matrix[x+i][y+j]='#';}
}
}
return count;
}

int solve(vector<vector<char>> matrix)


{
int m = matrix.size();
int n = matrix[0].size();
int num = 0;
int count = 0;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(matrix[i][j]=='*')
{
count = max(count,BFS(i,j,matrix));
num++;
}
}

程序设计 17
return num;
}

数据结构
稀疏矩阵(23)
class SparseMatrix
{
private:
int m;
int n;
vector<trible> terms;
public:
void multi(SparseMstrix rhs)
{
if(col!=rhs.row)
return;
else
{

}
}

};

struct trible
{
int row;
int col;
int val;
};

程序设计 18
用栈实现队列(22)
#include <bits/stdc++.h>
using namespace std;

class MyQueue {
public:
stack<int> leftout;
stack<int> rightin;
int size = 0;
MyQueue() {
}

void push(int x) {
rightin.push(x);
size++;
}

int pop() {
if(!leftout.empty())
{
int s = leftout.top();
leftout.pop();
size--;
return s;
}
else
{
while(!rightin.empty())
{
leftout.push(rightin.top());
rightin.pop();
}
int s = leftout.top();
leftout.pop();
size--;

程序设计 19
return s;
}
}

int peek() {
if(!leftout.empty())
{
int x = leftout.top();
return x;
}
else
{
while(!rightin.empty())
{
leftout.push(rightin.top());
rightin.pop();
}
int s = leftout.top();
return s;

bool empty() {
if(size==0)
return true;
else
return false;
}
};

/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);

程序设计 20
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/

用队列实现栈(22)
class MyStack {
public:
int size;
queue<int> arrin;
queue<int> arrout;
MyStack() {
size = 0;
}

void push(int x) {
size++;
arrin.push(x);
}

int pop() {
size--;
int last = -10000;
while(!arrin.empty())
{
last = arrin.front();
arrin.pop();
if(!arrin.empty())
arrout.push(last);
else
return last;
}
while(!arrout.empty())
{

程序设计 21
last = arrout.front();
arrout.pop();
if(!arrout.empty())
arrin.push(last);
else
return last;
}
return 0;
}

int top() {
int last = -10000;
while(!arrin.empty())
{
last = arrin.front();
arrin.pop();
arrout.push(last);
if(arrin.empty())
return last;
}
while(!arrout.empty())
{
last = arrout.front();
arrout.pop();
arrin.push(last);
if(arrout.empty())
return last;
}
return 0;
}

bool empty() {
if(size==0)
return true;
else
return false;

程序设计 22
}
};

C库函数
KMP 实现strstr(22)
void getNext(int *next,const string& s)
{
int j = 0;
next[j] = 0;
while(int i = 1;i<s.size();i++)
{
while(j>0&&s[j]!=s[i])
j = next[j-1];

if(s[i]==s[j])
j++;

next[i] = j;
}
}

int strStr(string haystack,string needle)


{
if(needle.size()==0)
return 0;
int next[needle.size()];
getNext(next,needle);
int j = 0;
for(int i=0;i<haystack.size();i++)
{
while(j>0&&haystack[i]!=needle[j])
j = next[j-1];

程序设计 23
if(haystack[i]==needle[j])
j++;

if(j==needle.size())
return i-needle.size()+1;
}
return -1;
}

两种方法实现strcpy(19)
// 方法 ,用数组
2 // 方法 ,用指针
1
void strcpy(char str1[],char s char* strcpy(char* str1,const
{ {
assert(str1!='\0'&&str2!= assert(str1!=NULL&&str2!=N
int index = 0; char* res = str1;
do{ while(str2!='/0')
str1[index] = str2[ind {
index++; *str1 = *str2;
}while(str2[index]!='/0') str1++;
return; str2++;
} }
} *str1 = '/0';
return res;
}

strncpy

char* strncpy(char* str1,const char* str2,int len)


{
assert(str1!=NULL&&str2!=NULL&&len<=((strlen(str1)<strlen(st
char* res = str1;
while(len--!=0&&(*str1++=*str2++)!='\0');

程序设计 24
return res;
}

实现strcat函数(20)
void strcat(char *str1,char* str2)
{
assert(str1!=NULL&&str2!=NULL);
while(str1!='\0')
str1++;
while(str2!='\0')
{
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}

power

double power(double base,double exp)


{
if(exp==0)
return 1;
else if(exp==1)
return base;
else if(exp<0)
return 1.0/power(base,-exp);
else if(exp%2==0)
{
double half = power(base,exp/2);
return half*half;
}
else

程序设计 25
{
double half = power(base,exp/2);
return half*half*base;
}
}

strlen

int strlen(char* str)


{
int len = 0;
while(*str!='\0')
{str++;i++;}
return i;
}

strcmp

int strcmp(char* str1,char* str2)


{
assert(str1!=NULL&&str2!=NULL);
if(strlen(str1)<strlen(str2))
return -1;
else
if(strlen(str1)>strlen(str2))
return 1;
else
{
while(*str1!='\0')
{
if(*str1==*str2)
{
str1++;
str2++;
}

程序设计 26
else
if(*str1<*str2)
return -1;
else
return 1;
}
return 0;
}
}

strncmp

int strncmp(char* str1,cha* str2,int len)


{
assert(str1!=NULL&&str2!=NULL&&len<=((strlen(str1)<strlen(st
while(len!=0&&*str1==*str2)
{str1++;str2++;}
return *str1-*ttr2;
}

程序设计
表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> num;
int n = tokens.size();
for(int i=0;i<n;i++)
{
string str = tokens[i];
if(str!="+"&&str!="-"&&str!="*"&&str!="/")
{

程序设计 27
num.push(stoi(str));
}
else
{// 注意这里要倒着运算
int a = num.top();
num.pop();
int b = num.top();
num.pop();
if(tokens[i]=="+")
num.push(a+b);
else
if(tokens[i]=="-")
num.push(b-a);
else
if(tokens[i]=="*")
num.push(a*b);
else
num.push(b/a);
}
}
int res = num.top();
return res;
}
};

链表的归并排序
class Solution {// 非递归自底向上
public:
ListNode* sortList(ListNode* head) {
if (head == nullptr) {
return head;
}
int length = 0;
ListNode* node = head;

程序设计 28
while (node != nullptr) {
length++;
node = node->next;
}
ListNode* dummyHead = new ListNode(0, head);
for (int subLength = 1; subLength < length; subLength <<
ListNode* prev = dummyHead, *curr = dummyHead->next;
while (curr != nullptr) {
ListNode* head1 = curr;
for (int i = 1; i < subLength && curr->next != n
curr = curr->next;
}
ListNode* head2 = curr->next;
curr->next = nullptr;
curr = head2;
for (int i = 1; i < subLength && curr != nullptr
curr = curr->next;
}
ListNode* next = nullptr;
if (curr != nullptr) {
next = curr->next;
curr->next = nullptr;
}
ListNode* merged = merge(head1, head2);
prev->next = merged;
while (prev->next != nullptr) {
prev = prev->next;
}
curr = next;
}
}
return dummyHead->next;
}

ListNode* merge(ListNode* head1, ListNode* head2) {


ListNode* dummyHead = new ListNode(0);

程序设计 29
ListNode* temp = dummyHead, *temp1 = head1, *temp2 = hea
while (temp1 != nullptr && temp2 != nullptr) {
if (temp1->val <= temp2->val) {
temp->next = temp1;
temp1 = temp1->next;
} else {
temp->next = temp2;
temp2 = temp2->next;
}
temp = temp->next;
}
if (temp1 != nullptr) {
temp->next = temp1;
} else if (temp2 != nullptr) {
temp->next = temp2;
}
return dummyHead->next;
}
};

class Solution {// 递归自顶向下


private:
// 确定中间节点
ListNode* split(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head->next;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* second = slow->next;
slow->next = nullptr;
return second;
}

程序设计 30
// 合并排序链表
ListNode* merge(ListNode* head1, ListNode* head2) {
ListNode* dummy = new ListNode();
ListNode* cur = dummy;
while (head1 != nullptr && head2 != nullptr) {
if (head1->val < head2->val) {
cur->next = head1;
head1 = head1->next;
}
else {
cur->next = head2;
head2 = head2->next;
}

cur = cur->next;
}
cur->next = (head1 == nullptr) ? head2 : head1;

ListNode* ret = dummy->next;


delete dummy;
dummy = nullptr;
return ret;
}

public:
ListNode* sortList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* head1 = head;
ListNode* head2 = split(head);

head1 = sortList(head1);
head2 = sortList(head2);

return merge(head1, head2);

程序设计 31
}
};

( )
atoi 23

int atoi(string str)


{
long long res = 0;
int index = 0;
int n = str.size();
while(index<n&&str[index]==' ')
index++;

bool reverse = false;


if(str[index]=='-')
{reverse = true;index++;}
else
if(str[index]=='+')
{index++;}

for(int i = index;i<n;i++)
{
int curdata = str[i]-'0';
if(curdata<=9&&curdata>=0)
{
res = res*10+curdata;//-2^32, 2^32-1
if(reverse&&res>=pow(2,31))
return -pow(2,31);
else
if(!reverse&&res>=(pow(2,31)-1))
return pow(2,31)-1;
}
else
break;
}

程序设计 32
if(reverse)
return -res;
else
return res;
}

实现atof(18)
float atof(string str)
{
int index = 0;
double res = 0.0;
bool reverse = false;
int n = str.size();
while(str[index]==' ')
{index++;}

if(str[index] = '-')
{reverse = true;index++;}
else
if(str[index] = '+')
{index++;}

if(str[index]-'0'<0||str[index]-'0'>9)
return 0.0;

while(0<=str[index]-'0'&&str[index]-'0'<=9)
{
int curdata = str[index]-'0';
res = res*10.0+curdata;
index++;
}

if(str[index]=='.')
index++;

程序设计 33
int r = 1;
while(0<=str[index]-'0'&&str[index]-'0'<=9)
{
float curdata = str[index]-'0';
res = res+curdata/pow(10,r);
r++;
index++;
}

if(str[index]=='e'||str[index]=='E')
{
index++;
int count = 0;
if(str[index]=='-')
{
index++;
while(0<=str[index]-'0'&&str[index]-'0'<=9)
{
count = count*10+str[index]-'0';
str++;
}
while(count!=0)
{
res = res/10;
count--;
}
}
if(str[index]=='+')
{
index++;
while(0<=str[index]-'0'&&str[index]-'0'<=9)
{
count = count*10+str[index]-'0';
str++;
}

程序设计 34
while(count!=0)
{
res = res*10;
count--;
}
}
}
if(reverse)
return -res;
else
return res;
}

高精度2to10(23)
string Div(string s,int b)
{
int x = 0;
string ans = '';
vector<int> a(s.size());
vector<int> c(s.size());
for(int i=0;i<s.size();i++)
a[i] = s[i]-'0';

for(int i=0;i<s.size();i++)
{
c[i] = (x*10+a[i])/b;//当前位加上前一位的余数*10再÷2
x = (x*10+a[i])%b;// 获得这一位的余数
}

int lc = 0;
while(c[lc]==0&&lc<s.size())
lc++;
for(int i=lc;i<s.size();i++)
ans+=c[i]+'0';

程序设计 35
return ans;

string transforme10to2(string data)


{
string res;
while(data.size()!=0)
{
最后一位对2取余
res+=to_string(data[data.size()-1]-'0'%2);//
data = Div(data,2);// 模拟 操作
÷2
}
reverse(res.begin(),res.end());//因为放余数是反着放的

grep

void mygrep(string fpath,string str,bool print_line_numbers,int


{
ifstream fp(fpath);
string line;
int count = 0;
int line_printed = 0;
while(getline(fp,line))
{
count++;
if(line.find(str)!=-1)
{
if(print_line_numbers)
cout<<count<<": ";
cout<<line<<endl;
line_printed++;
if(line_printed==max_lines)

程序设计 36
break;
}
}
fp.close();
return;
}

文件操作:给你一个文件的路径,该文件内是一篇英语文章,你需要读
出该文件内的词频最高的前K个单词(18)
#include <bits/stdc++.h>
using namespace std;

bool cmp(pair<string,int> a, pair<string, int> b) {


从小到大排序
return a.second > b.second;//
}

vector<pair<string,int> > topkwords(string fpath,int k)


{
ifstream fp(fpath);
string buf;
map<string,int> mp;
while(getline(fp, buf))
{
int i = 0;
while(i<buf.size())
{
string word;
while((0>buf[i]-'a'||buf[i]-'a'>25)&&(0>buf[i]-'A'|
i++;
while((0<=buf[i]-'a'&&buf[i]-'a'<=25)||(0<=buf[i]-'A
{
word = word+buf[i];
i++;
}

程序设计 37
mp[word]++;
}
}
vector<pair<string,int> > res(mp.begin(),mp.end());
sort(res.begin(),res.end(),cmp);
return vector<pair<string,int>>({res.begin(), res.begin() +
}

int main()
{
string fpath = "data.txt";
vector<pair<string,int>> topk = topkwords(fpath,5);
for(auto x : topk)
cout<<x.first<<":"<<x.second<<endl;
system("pause");
return 0;
}

fgetsfputs

FILE* fp = fopen("demo.txt","r");
FILE* fpout = fopen("output.txt","w");
char buf[1024];
while(fgets(buf,1024,fp)!=NULL)
{
fputs(buf,fpout);
puts(buf);
}
return;

getcputc

char ch = fgetc(fp);
while(ch!=EOF)
{

程序设计 38
//putchar(ch);
putc(ch,fp2);
ch = fgetc(fp);
}
fclose(fp);

getline

string str;
while(getline(cin, str))// 每一组数据都能收集一次
{
int n = str.size();
int res = 0;
for(int i = 0; i < n; i++)
{
res+=int(str[i])-96;
}
cout<<res<<endl;
}

专业/人数 考研 保研 总人数
电子信息(博) / / 10

电子信息(硕) 30 3 33

金融科技(硕) 22 12 34

数字经济(硕) 9 14 23

程序设计 39

You might also like