简体   繁体   English

这个布尔数组如何工作?

[英]How does this Boolean array work?

I don't understand how this code works. 我不明白这段代码是如何工作的。 The problem is find the next year after a given year with distinct digits. 问题是在给定年份后的第二年用不同的数字查找。

public Main(){
    try{
        BufferedReader in;
        in = new BufferedReader (new InputStreamReader (System.in)); //Used for CCC
        String year = (in.readLine());
        for(int i = Integer.parseInt(year)+1;; i++){
            String f = Integer.toString(i);
            boolean [] characters = new boolean[10];
            boolean unique = true;
            for(int x = 0; x < f.length(); x++){
                if (characters[f.charAt(x) - '0']){
                    unique = false;
                    break;
                }
                else{
                    characters[f.charAt(x)-'0'] = true; 
                }
            }   
            if (unique){
                System.out.println(f);
                return; 
            }

Specifically how does this if statement work? 具体来说,如果语句如何工作?

if (characters[f.charAt(x) - '0']){

what does checking a boolean do here? 在这里检查布尔值有什么用? Shouldn't they all be defaulted to false? 难道不都将它们默认设置为false吗? and why is the -'0' there? 为何-0在那里? Sorry for the noob question. 对不起,菜鸟问题。

The expression 表达方式

f.charAt(x) - '0'

will return a number between 0 and 9 depending on the digit at position x in the String f . 将返回0到9之间的数字,具体取决于String f中位置x处的数字。 Hence the code will set a boolean flag at each of the 10 digit positions in the array, and if a digit occurs more than once, then it will report false and break out of the inner loop to consider the following year. 因此,代码将在数组的10个数字位置的每个位置设置一个布尔标志,并且如果一个数字出现多次,则它将报告false并退出内部循环以考虑下一年。

characters is a boolean array of 10 elements and stores whether a given input character (which are supposed to be limited to decimal digits) appears more than once in the input. characters是一个由10个元素组成的布尔数组,用于存储给定的输入字符(应该限制为十进制数字)是否在输入中出现多次。

Character codes for digits are in the 0x30 - 0x39 range; 数字的字符代码在0x30-0x39范围内; f.charAt(x) returns the character at index x in the input and then - '0' transforms it into a number in the range of 0 - 9 - an index into the boolean array. f.charAt(x)返回输入中索引x处的字符,然后f.charAt(x) - '0'将其转换为0-9范围内的数字-布尔数组的索引。

When a character is first found, its slot is set to true ; 首次找到字符时,其插槽设置为true when it's found again, unique is set to false to indicate that the input has duplicate characters. 再次找到时,将unique设置为false以指示输入具有重复字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM