codewars 一道题 Highest and Lowest

Problem

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
输入是一个字符串,输出最大数和最小数。

Note

All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.

Solution

#include <string>
#include <sstream>  //这是C++引入的,可以对串流做输入输出处理。
#include <limits>   //这个头文件对应下面的最大值和最小值
using namespace std;
string highAndLow(const string& numbers){
  string number=numbers;
  int max=numeric_limits<int>::min();  //返回编译器允许的最小值
  int min=numeric_limits<int>::max();  //返回编译器允许的最大值
  int temp;
  stringstream ss(numbers);  //ss的值现在是number的值
  while(ss>>temp)
  {
  if(temp<min){min=temp;}
  if(temp>max){max=temp;}
  }
  return to_string(max)+" "+to_string(min);
}

这代码真简洁,每次看到大佬的代码都佩服的不行。
关于stringstream的用法,转载以为大佬的一下代码:
(转载自https://blog.csdn.net/Sophia1224/article/details/53054698)

#include <sstream>
#include <iostream>
using namespace std;
int main() {
	ostringstream out;
	out.put('t');//插入字符
	out.put('e');
	out << "st";   //这里是输入的意思。
	string res = out.str();//提取字符串;
	cout << res << endl;
	return 0;
}
//输出是 test 字符串。

#include<iostream>
#include <sstream> 
using namespace std; 
int main() {
	string test = "-123 9.87 welcome to, 989, test!";
	istringstream iss;//istringstream提供读 string 的功能
	iss.str(test);//将 string 类型的 test 复制给 iss,返回 void 
	string s;
	cout << "按照空格读取字符串:" << endl;
	while (iss >> s) {
		cout << s << endl;//按空格读取string
	}
	cout << "*********************" << endl;

	istringstream strm(test);
	//创建存储 test 的副本的 stringstream 对象
	int i;
	float f;
	char c;
	char buff[1024];

	strm >> i;
	cout << "读取int类型:" << i << endl;
	strm >> f;
	cout << "读取float类型:" << f << endl;
	strm >> c;
	cout << "读取char类型:" << c << endl;
	strm >> buff;
	cout << "读取buffer类型:" << buff << endl;
	strm.ignore(100, ',');
	int j;
	strm >> j;
	cout << "忽略‘,’读取int类型:" << j << endl;
	return 0;
}

在这里插入图片描述
这个里面代码讲解的很细致。大佬。
结束!

发布了27 篇原创文章 · 获赞 0 · 访问量 411

猜你喜欢

转载自blog.csdn.net/weixin_40007143/article/details/104101235
今日推荐