1694.重新格式化电话号码
链接:1694.重新格式化电话号码
难度:Easy
标签:字符串
简介:返回格式化后的电话号码。
题解 1 - cpp
- 编辑时间:2022-10-01
- 执行用时:12ms
- 内存消耗:11.9MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    string reformatNumber(string number) {
        string tmp = "", ans = "";
        for (auto &c : number) {
            if (c != '-' && c != ' ') tmp += c;
        }
        int len = tmp.size(), idx = 0;
        while (len > 4) {
            ans += to_string(tmp[idx++] - '0') + to_string(tmp[idx++] - '0') + to_string(tmp[idx++] - '0') + "-";
            len -= 3;
        }
        if (len == 4) {
            ans += to_string(tmp[idx++] - '0') + to_string(tmp[idx++] - '0') + "-" + to_string(tmp[idx++] - '0') + to_string(tmp[idx++] - '0');
        } else {
            while (idx < tmp.size()) ans += to_string(tmp[idx++] - '0');
        }
        return ans;
    }
};