题解 | 表示数字

表示数字

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

用一个count变量保存连续数字串的长度,如果遇到数字,count为0说明该数字是第一个数字,则追加一个星号,再将当前数字添加进去;如果没有遇到数字,检查count,若大于0,则说明前面有count个连续数字,追加一个星号,count置为0,将当前字符添加进去

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();
        int count = 0, length = line.length();

        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < length; i++) {
            char ch = line.charAt(i);

            if(ch >= '0' && ch <= '9') {
                if(count == 0) {    // 第一个连续数字
                    sb.append("*");
                }
                sb.append(ch);
                count++;
            } else {
                if(count > 0) sb.append("*");
                sb.append(ch);
                count = 0;
            }
        }
        if(count > 0) sb.append("*");   // 处理最后一个字符是数字的情况
        System.out.println(sb.toString());
    }
}
全部评论

相关推荐

钱嘛数字而已:辅导员肯定不能同意,不然你出事了,他要承担责任。但是,脚和脑子都长在你自己身上,使用它还需要向辅导员报告么? 辅导员必须按流程拒绝你,然后你拿出成年人的态度,做自己的选择。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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