找座位-逻辑分析题

本文详细解释了一个Java程序,通过Scanner读入用户输入的字符数组,计算并输出可以坐下的空位数量,涉及数组操作和条件判断逻辑。
摘要由CSDN通过智能技术生成

在这里插入图片描述
在这里插入图片描述

import java.util.Scanner;
public class Main{
    public static void main(String []args){
        Scanner in = new Scanner(System.in);

        String inString = in.nextLine();
        char[] temp = inString.toCharArray();
        int [] tempInt = new int[temp.length];
        int i = 0;
        for(char tempChar:temp){
            tempInt[i] = tempChar-'0';
            //System.out.print(tempInt[i]);
            i++;
        }
        // 记录能坐下的个数
        int count = 0;

        // 判断第一个元素的位置  是否能坐下
        if(tempInt[0] == 0){
            if(tempInt.length>1){
                if(tempInt[1] == 0){
                    count++;
                    tempInt[0] = 1;
                }
            }
            else{
                // length == 1 且 为空位 的条件下
                count++;
                tempInt[0]=1;
            }
        }

        // 掐头去尾 判断中间能否坐下
        for(int j=1;j<(tempInt.length-1);j++){
            if(tempInt[j] == 0 && tempInt[j-1] == 0 && tempInt[j+1] == 0){
                count++;
                tempInt[j]=1;
            }
        }

        // 判断末尾能否坐下
        if(tempInt.length>1 && tempInt[tempInt.length-2]==0 && tempInt[tempInt.length-1]==0){
            count++;
            tempInt[tempInt.length-1] = 1;
        }

        System.out.println(count);

    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值