Saturday, August 20, 2022

Find missing integer in Java

 This is the program to find the missing numbers in the first n integers.


public static int findMissingNumber(int[] nums) {
int n = nums.length + 1;
// formula for sum of first n integers is n*(n+1)/2
// but we have n+1 integers as one integer is missing
int sum = (n * (n + 1)) / 2;
for (int i = 0; i < nums.length; i++) {
sum -= nums[i];
}
return sum;
}

No comments:

Post a Comment

Ruby Basics

Basics of Ruby   Start Ruby interpret On terminal just type rib ruby_docs $ irb 3 . 0 . 0 : 001 > name = "This is the first ...