传说百度面试题,都是字符串处理的……我目前这水平也就做这种水题了,下午莫名其妙被面试,坐等被虐了。
1、反转字符串单词。
输入I am coder4
输出coder4 am i
#include <iostream> #include <vector> #include <sstream> using std::endl; using std::cout; using std::istringstream; using std::vector; using std::string; int main() { vector<string> vec; istringstream iss("I am Jack Chen"); string part; while(iss>>part) { vec.push_back(part); } for(int i = vec.size()-1; i>=0; i--) { cout<<vec[i]<<" "; } cout<<endl; }
2、将string形式的浮点数转化成double/float,只允许一次遍历。
输入:123.456(string)
输出:123.456(double/float)
#include <iostream> #include <string> using std::ios; using std::cout; using std::endl; using std::string; int main() { string str("11111.222"); bool dn = true; double part1 = 0, part2 = 0; double tmp = 1; for(int i=0;i<str.length();i++) { if(str[i]=='.') { dn = false; continue; } if(dn) { part1 *= 10; part1 += (str[i] - '0'); } else { tmp/=10; part2 += (str[i] - '0')* tmp; } } cout.precision(str.length() - 1); cout<<(part1 + part2)<<endl; }