简体   繁体   中英

Wrong answer when multiplying variables

I'm trying to multiply two variables. One is an int and the other is inside a char array.

My code is this

int biggestProduct = 1;
int currProduct = 1;
char[] array = num.toCharArray();

for (int x = 0; x < array.length; x++) {
    if (x < 5) {
        System.out.println(currProduct + " * " + array[x] + " = " + currProduct * array[x]);
        currProduct *= array[x];
    }
}

return biggestProduct;

The problem is with the currProduct*= array[x]

This is my output when I print it out:

1 * 7 = 55
55 * 3 = 2805
2805 * 1 = 137445
137445 * 6 = 7422030
7422030 * 7 = 408211650

Why isn't it multiplying correctly?

The problem is that the numeric value of the char 7 is not 7 but 55 .

Because in Java, the char data type is a single 16-bit Unicode character (see encoding table below).

在此输入图像描述

If you take a look at this table, you see that 7 is encoded as 0x0037 = 3*16^1 + 7 = 55 .

If you want to take the real numeric value of your character, you can use Character.getNumericValue(char ch) :

 char ch = '7';
 int number = Character.getNumericValue(ch);
 System.out.print(number); //print 7

So to edit your code, it will looks like :

        String num = "73167";
        int biggestProduct = 1;
        int currProduct = 1;
        char[] array = num.toCharArray();

        for (int x = 0; x < array.length; x++) {
            if (x < 5) {
                System.out.println(currProduct + " * " + array[x] + " = " + currProduct * Character.getNumericValue(array[x]));
                currProduct *= Character.getNumericValue(array[x]);
            }

        }

Output :

1 * 7 = 7
7 * 3 = 21
21 * 1 = 21
21 * 6 = 126
126 * 7 = 882

Verification : 7*3*1*6*7 = 882

Try like this:

currProduct *= (int) array[x];

Check here for what the char values usually represent. You will see that if you want your char to hold the numerical value 2, you have to actually assign 50:

char two = 50;
System.out.println(two); // prints out 2

The value of '7' is 55 because it is just another character like eg 'a', so its numeric value will be its ASCII code. See here: http://www.asciitable.com/
(Note that the used ASCII table can be also implementation dependant.)

The numeric value of '7' isn't 7, it's 55. This is like any character, for example the character 'A' is 65

For example

public class Calendar
{
    public static void main(String[] args){
        char testChar='7';
        int testInt=testChar;

        System.out.println(testInt); //prints 55
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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