简体   繁体   中英

converting string to Integer val

if my String contains 100 digits or 900 digits how can i parse it to Integer value Java.

public static void main(String...args){
    long answer1=-1,answer2=-1;
    Scanner sc = new Scanner(System.in);
    int m = sc.nextInt();//length
    int s = sc.nextInt();//sum
    String startNmbr="1",endNmbr="9";
    int startRange=1,endRange=9;
    for(int i=1;i<m;i++){
        startNmbr+="0";endNmbr+="9";endRange+=9;
    }
    long end = Long.parseLong(endNmbr);
    for(long start=Long.parseLong(startNmbr);start<=end;start++){
        if(answer1==-1 && countNmbr(start)==s){
            answer1=start;
        }
        if(answer1!=-1 && countNmbr(start)==s){
            answer2=start;
        }
    }
    System.out.println(answer1+" "+answer2);
}
public static int countNmbr(long a){
    int answer=0;
    String str = a+"";
    for(int i=0;i<str.length();i++){
        answer+=(str.charAt(i)-'0');
    }
    return answer;
}

My input was 100,100; I must return the min and max values that their length==m and sum == s;

Integer's MAX_VALUE is 2,147,483,647. Which is 10 digits.

You can use BigInteger - No Limit , but it depends on your memory and system architecture.

You cannot parse you 900 digits of number into Integer because theoretically, Integer has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 ( see java docs on Integer )

Big Integer however will fulfill your use case since theoretically it has the range of -2^Integer.MAX_VALUE(2,147,483,647) to +2^Integer.MAX_VALUE(2,147,483,647).

In your code you can just parse the string like this :

BigInteger end = new BigInteger(endNmbr);

and change all long type into BigInteger and you'll good to go.

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