In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Examples
highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"
Notes
- 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.
要点
sstringstream
实现对字符串用空白进行分割, 并转换为数字.<sstream>
numeric_limits
获取int的上界和下界 作为max/min变量的初始值.<limits>
std::to_string
将数字转换为字符串.<string>
分析
需要解决的问题主要有两个:用空格分隔出子串;以及将每个子字符串转为数字。
sstringstream
就能完美解决这个问题。
sstringstream
默认以空格为分隔符输出字符串,并且通过ss >> 数字类型变量
完成类型转换.
此外还有一个细节问题, 即max
和min
变量的初始值. 因为后续过程中对这两个变量的更新是基于新的数值和max/min
的比较的.
因此必须选取合适的初值才能使后续的更新正常进行.
对于max
, 需要选个尽量小的数, 这样数字序列中的最大值才能比它大,进而用该值更新它.对min
也是类似, 需要选一个尽量大的值作为初始值.
因此需要表示int的上下界.(因为此题目数字范围用int即可描述)
这需要用numeric_limits
这个类: std::numeric_limits::max() / min()
#include <string>
#include <sstream>
#include <limits>
std::string highAndLow(const std::string& numbers){
std::stringstream ss {numbers};
int max{std::numeric_limits<int>::min()} ;
int min{std::numeric_limits<int>::max()} ;
int current{};
while( ss >> current){
max = current> max? current : max ;
min = current< min ? current :min;
}
return std::to_string(max)+" " + std::to_string(min);
}