智算之道初赛第一场-开关

在这里插入图片描述

import java.util.Scanner;

public class Main2 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); //开关数量
        String s = sc.next(); //定义一个字符串
        char[] a =s.toCharArray(); //将字符串转化为字符数组
        int count = 0; //操作次数

        //相邻字符是否一样,如果不一样操作次数就加一
        for (int i = 0; i < a.length - 1; i++) {
            if(a[i] != a[i + 1]){
                count++;
            }
        }
        //利用三元判断字符串最后一位是否为'0'
        System.out.println(a[a.length - 1] == '0' ? count : ++count);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33591873/article/details/107306729