去除前导 0 的经典代码


【算法分析】
● 前导 0(Leading Zero)指的是出现在数字或字符串开头、且在第一个非 0 数字之前的所有 0。
例如,"00123" 的前导 0 是开头的两个 0,去除后应为 "123";"000" 没有非 0 数字,去除前导 0 后通常保留一个 0(而非空字符串);"12030" 没有前导 0。

【算法代码】

#include <bits/stdc++.h>
using namespace std;

string RLZ(string &str) { //Remove Leading Zeros
    int p=0; //pos
    if(str[0]=='-') p=1;
    while(p<str.size() && str[p]=='0') {
        str.erase(p,1); //Delete str[p]
    }
    if(str=="-") return "-0";
    if(str.empty()) return "0";

    return str;
}

int main() {
    int T;
    cin>>T;
    while(T--) {
        string s;
        cin>>s;
        cout<<RLZ(s)<<endl;
    }

    return 0;
}

/*
in:
6
00123
000
12030
-00123
-000
001020

out:
123
0
12030
-123
-0
1020
*/

 

 

【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/157836967

 

posted @ 2026-02-08 09:29  Triwa  阅读(22)  评论(0)    收藏  举报