【codewars-3】从字符串形式的数字序列中找出最大和最小值

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 >> 数字类型变量完成类型转换.

此外还有一个细节问题, 即maxmin变量的初始值. 因为后续过程中对这两个变量的更新是基于新的数值和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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值