Friday, October 3, 2014

Sum of numbers in array and ignoring numbers between 6&7

Ques: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

Ans:
public static int sum67(int[] nums) {
        int sum = 0;
        for(int i=0;i<nums.length;i++){
           
            if(nums[i]==6){
             do{
                i++;
            }while (nums[i]!=7);  
            }else{
                sum+=nums[i];
            }
           
        }
       
        return sum;

    }

No comments:

Post a Comment