我的任务是输出给定日期的当前世纪。日期可以表示为string;例如,19.03.2022。
我怎样才能找回这些弦的年代和世纪呢?
发布于 2020-07-08 22:12:39
string date = "19.03.2022";
int century = (date[6] - '0') * 10 + (date[7] - '0');
if(date[8] != '0' || date[9] != '0') century++;
cout<<century<<endl;输出:21
复杂性: O(1)
发布于 2020-07-08 21:27:22
给定string的年份总是包含在最后四个字符中,因此可以使用string::substr和std::stoi检索该年份:
string str = "19.03.2022";
int year = stoi(str.substr(6, 4)); // year = "2022"在此之后,您可以使用year计算世纪:
int century = year/100 + 1; // century = 21https://stackoverflow.com/questions/62803823
复制相似问题