简体   繁体   中英

Getting negative numbers from multiplying positive in java

My question has to do with problem 8 from project Euler: Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

I would think that my program should be able to solve this but I keep getting weird results. For debugging reasons I have printed out every 13 digit product. Some of these are negative even though there are no negative digits in the 1000-digit number. I've been stuck on this for quite a while now so if anybody could help me with this it would be greatly appreciated.

    import java.io.*;

public class Highest13 {
public static void main(String[] args) throws FileNotFoundException {
    File input = new File("number1000.txt");
    Scanner in = new Scanner(input);
    long number = 1L;
    long highest = 1L;
    char c = '1';
    String given = "";

    in.useDelimiter("");
    while (in.hasNext()) {
        given += in.next();
    }

    for (int i = 0; i < given.length()-12; i++) {
        for (int j = 0; j <= 12; j++) {
            c = given.charAt(i + j);
            number = number * Character.getNumericValue(c);
        }
        System.out.println(number); //printed for debugging --> gives negative numbers
        if (number > highest) {
            highest = number;
        }
        number = 1L;
    }
    System.out.println(highest);
}
}

If any character is not a digit, eg space or new line Character.getNumericValue(c) returns -1

I suggest removing non-digit characters when you build up your String so you can assume there are non there.

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