Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputted integer to char array - Java

Tags:

So I recently attempted to do the HackerRank challenge that involved counting a number's holes and adding them up, and after a bit of research, I ended up making it into a char array and choosing three values to increment and add up to the sum as shown below:

 public static int countHoles(int num) {

    //create integers that count how many a number with no, one or two holes shows up
    Integer noHoles = 0;
    Integer oneHole = 0; 
    Integer twoHoles = 0; 
    Integer sum = 0;
    Integer length = 0;

    //turn the inputted number into a char array
    char [] digits = String.valueOf(num).toCharArray();
    System.out.println(digits);
    length = digits.length;

    //These nested loops incremement the numbers initialized above as the first for-each loop goes through each index value of the array
    for (int i = 0; i < digits.length; i++){
        if (digits[i]== 1 || digits[i]==2 || digits[i]==3 || digits[i]==5 || digits[i]==7){
            noHoles++;
        } else if (digits[i]==4 || digits[i]==6 || digits[i]==9 || digits[i]==0){
            oneHole+= 1;
        } else if (digits[i]==8){
            twoHoles+= 2;
        }

    }
    //add up the incremented integers. twoHoles is doubled as each unit counts as two holes and noHoles is 0 regardless of its values
    sum = oneHole + twoHoles;
    return sum;
    }
}

but the char array always return as a normal integer! I can't try the modulus approach since 0 is used (has one hole in it), and a bunch of variants on String.valueOf(num).toCharArray() such as ("" + num).toCharArray() and Integer.toString(number).toCharArray(), but it stills outputs the inputted number instead of the wanted char array. Of course, the rest of the method spits out 0 because of the empty array too.

I'm a bit of a newbie, but damn is this frustrating. I feel like it's a micro-detail I haven't seen or don't know instead of my logic. Any help please?

like image 807
T. Bifo Avatar asked Nov 12 '18 19:11

T. Bifo


People also ask

How do I convert an int to a char array in Java?

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.

How do I convert a number to a char array?

Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number. Separating integer into digits and accommodate it to a character array.

Can we assign integer value to char?

Because, char are data types which hold 1 byte (8 bits) of data. So in char you can store integer values that can be represented by eight bits. That is 0-255 in normal case. So you can store values in that range in char.

Can we add int to char in Java?

In Java, char and int are compatible types so just add them with + operator. c + x results in an integer, so you need an explicit casting to assign it to your character varaible back.


2 Answers

You're comparing a char to an int with the incorrect int values (for example, '1' != 1). It would safer to compare char to char:

if (digits[i] == '1' || digits[i] == '2' || digits[i] == '3' || digits[i] == '5' || digits[i] == '7') {
    noHoles++;
} else if (digits[i] == '4' || digits[i] == '6' || digits[i] == '9' || digits[i] == '0') {
    oneHole += 1;
} else if (digits[i] == '8') {
    twoHoles += 2;
}

You also don't need the noHoles variable, as it goes unused after it's incremented. If you remove noHoles, you can also remove the first if-statement where you check if the number is 1, 2, etc.

Also to print your char[], use Arrays#toString:

System.out.println(Arrays.toString(digits));
like image 120
Jacob G. Avatar answered Nov 15 '22 05:11

Jacob G.


First, you must add some quotes to your test since digits[i] is a char, you can not compare them this way. digits[i]== '1' works. For instance :

    char five = '5';
    if (five == 5) {
        System.out.println("They are similar");
    } else {
        System.out.println("They are not similar");
    }

print not similar.

Second, System.out.println(digits) results in a call to print(char[] s) then println(), and if you check the javadoc of print(char[] s), it says :

Print an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

So it performs a byte-by-byte print out. So its normal that it prints an integer.

like image 38
Théo Pascoli Avatar answered Nov 15 '22 04:11

Théo Pascoli