完美世界2018春招编程题

    1. 题目描述:输入若干整数,以空格间隔,要求反转字符序列并打印输出。
      如:
  • Input: 12 3 456 6789

  • Output: 6789 456 2 12

  • 源代码:
    方法一、使用栈存储

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
#include <cstdio>
#include <stack>
#include <vector>
using namespace std;
int main()
{
int a[20];
int i = 0;
string ss, st;
stack<string> s1;
char c;
do{
c = getchar();
if(c >= '0' && c <= '9'){
ss += c;
}else if(c == ' ' || c == '\n'){

s1.push(ss);
ss = "";
}
}while(c != '\n');

while(!s1.empty()){
st = s1.top();
s1.pop();
cout << st;
if(!s1.empty()){
cout << " ";
}else{
cout << endl;
}
}
return 0;
}

方法一、使用数组变换存储

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<bits/stdc++.h>	
using namespace std;

int main()
{
int a[20];
int i = 0;
char c;
string str = "";
do{
c=getchar();
if(c>='0'&&c<='9'){
str += c;
}else if(c ==' ' || c == '\n')
{
a[i++] = atoi(str.c_str()); //atoi:将字符串转化为char*对象,再转换成一个整数值
str = "";
}
}while(c!='\n');

for(int j = 0; j < i; j++){
cout << a[i-j-1];
if(i-j-1 != 0){
cout << " ";
}else{
cout << endl;
}
}
}
请我吃辣条吧~~ 谢谢打赏
0%