题解 | #字符逆序#

字符逆序

https://www.nowcoder.com/practice/cc57022cb4194697ac30bcb566aeb47b

#include <iostream>
#include <string.h>
using namespace std;

//将字符串最大长度声明为常量
constexpr int N = 6144;

//反转
//添加const避免指针及其所指内容被修改
void reverse(const char* const str) {
    int i = 0;
    //找出字符串尾部
    for (; i < N; i++)
        if (str[i + 1] == 0)
            break;
    //如果是空串,则什么也不输出
    if (i == 0) {
        cout << endl;
        return;
    }
    //反向输出
    for (; i >= 0; i--)
        cout << str[i];
    cout << endl;
    return;
}

int main() {
    char* str  = new char[N];
    while (cin.getline(str, N)) { // 注意 while 处理多个 case
        //反转输出
        reverse(str);
        //清空
        memset(str, 0, N);
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务