这道题目很水。但是也要我不熟悉的知识点,substr();
整理如下:
substr是分割字符串,这个题目中,主要是为了截取除去0之外的字符。这个函数刚好与assgin函数相反,assgin函数是在字符前增加一些字符串,这个函数在前面的大数相加有用到过。
形式为:
string substr (pos,len);
pos 是要截取字符串的首个位置,注意原字符串从0计数。比如"123" substr(1),返回结果是23
len 是要截取的长度,可以不写,缺省的时候,以为截取到字符串结束为止。
c++reference中给出的例子为:
// string::substr #include <iostream> #include <string> int main () { std::string str="We think in generalities, but we live in details."; // (quoting Alfred N. Whitehead) std::string str2 = str.substr (12,12); // "generalities" std::size_t pos = str.find("live"); // position of "live" in str std::string str3 = str.substr (pos); // get from "live" to the end std::cout << str2 << ' ' << str3 << '\n'; return 0; }
4868的做法为:(感觉自己的代码不够精简,希望大家提出修改意见哈)
#include"iostream" #include"string" #include"algorithm" using namespace std; string reverse(string n){ int length = n.length(); for(int i = 0;i < length/2;i++){ char temp = n[i]; n[i] = n[length - i -1]; n[length - i -1] = temp; } if(n[0]-'0'==0){ int j; for(j = 0;j < length;j++){ if(n[j]-'0'!=0) break; } n = n.substr(j); } return n; } int main(){ string N; cin>>N; if(N == "0"){ cout<<0<<endl; }else if((N[0]-'0')>=1 && (N[0]-'0')<=9){ cout<<reverse(N)<<endl; }else{ N = N.substr(1,N.length()-1); cout<<"-"+reverse(N)<<endl; } system("pause"); return 0; }