题解 | #表示数字C++#

表示数字

http://www.nowcoder.com/practice/637062df51674de8ba464e792d1a0ac6

思路

1.接收字符串
2.遍历字符串,查找需要插入*的位置
3.在指定位置插入*

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

int main()
{
    string get;
    while(getline(cin, get))//接收字符串
    {
        int sz=get.size();
        vector<int> pos;//记录需要插入*的位置
        for(int i=0;i<sz;i++)//遍历字符串,确定插入*的位置
        {
            if(get[i]>='0'&&get[i]<='9')
            {
                pos.push_back(i); //数字前插入*。记录数字的具***置
                while(i<sz&&(get[i]>='0'&&get[i]<='9'))
                {
                    i++;
                }
                if(i==sz)//如果数字是字符串的末尾,则直接添加*
                    get.push_back('*');
                else//记录数字后第一个字符的位置
                {
                    pos.push_back(i);
                }
            }
        }
        for(int i=0;i<pos.size();i++)//进行*的插入
        {
            //每插入一个*,后一个插入位置向后移动一位
            //插入n个*后,低n+1个*往后移动n
            get.insert(pos[i]+i, "*");
        }
        cout<<get<<endl;
    }
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
转发
移动云能力 苏小妍 总包多3w左右
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务