0
import java.util.*;

public class Main
{
    public static int plusOne(int[] digits) {
        int no =0;
        for(int i=0; i< digits.length; i++){
            if(digits[i]==0){
                no = no*10;
            }
            else{
                no = no*10+ digits[i];
            }
            
        }
        no = no+1;
        return no;
    }
    public static void main(String[] args) {
        System.out.println("Hello World");
        int arr[] = {9,8,7,6,5,0,4,3,2,1,0};
        
        System.out.println(plusOne(arr));;
        
    }
}

EXPECTED OUTPUT:- 98765043211

OUTPUT:- -19204598

ISSUE:- In the last run when i ==9 , no change to some random value

I am trying to simply create a no by taking all the values from the array and adding one to it *Also try with double but it does not resolve the problem

  • 5
    Your sum is exceeding `Integer.MAX_VALUE` (2147483647) which then rolls negative and so on which in this case occurs at the 10th digit (from left) of your test. – Computable May 02 '23 at 18:19
  • 1
    You may want to use BigInteger for numbers that can not be represented with Java integers. – aled May 02 '23 at 19:12
  • In addition to previous comments, you don't need the `if (digits[i]==0)` – Andrés Alcarraz May 02 '23 at 19:37
  • Simple fix is to migrate from `int` to `long`. A long can store a number 4 billion times larger than an int. – knittl May 02 '23 at 20:41

0 Answers0