Java > Array-2 >has77 (CodingBat Solution)

Problem:

Given an array of ints, return true if the array contains two 7's next to each other, or there are two 7's separated by one element, such as with {7, 1, 7}.

has77({1, 7, 7}) → true
has77({1, 7, 1, 7}) → true
has77({1, 7, 1, 1, 7}) → false


Solution:

public boolean has77(int[] nums) {
boolean result = false;

  for (int i = 0; i < nums.length-1; i++)
  if ((nums[i] == 7 && nums[i+1] == 7))
  result = true;
  
   for (int i = 0; i < nums.length-2; i++)
  if ((nums[i] == 7 && nums[i+2] == 7))
  result = true;


5 comments :

  1. Why pass through twice?

    public boolean has77(int[] nums) {
    for(int i = 0; i<nums.length-1;i++)
    {
    if(nums[i]==7 && (nums[i+1]==7 || (i<nums.length-2&&nums[i+2]==7))) return true;
    }
    return false;
    }

    ReplyDelete
  2. public boolean has77(int [] nums){
    for(int x = 0; x < nums.length-2; x++){
    if(int[x] == 7 && int[x+1] == 7){
    return true;
    }
    if(int[x] == 7 && int [x+2] == 7){
    return true;
    }
    if(int[x+1] == 7 && int [x+2] == 7){
    return true;
    }
    }
    return false;
    }

    ReplyDelete
  3. public boolean has77(int[] nums) {
    boolean result = false;

    for (int i = 0; i < nums.length-1; i++)
    if ((nums[i] == 7 && nums[i+1] == 7))
    result = true;

    for (int i = 0; i < nums.length-2; i++)
    if ((nums[i] == 7 && nums[i+2] == 7))
    result = true;
    return result;
    }

    ReplyDelete
  4. public boolean has77(int[] nums) {
    boolean flag = false;

    for(int i = 0; i < nums.length-2; i++){
    if((nums[i] == 7 && nums[i +1] == 7)||
    (nums[i] == 7 && nums[i +2] == 7) ||
    (nums[nums.length-2] == 7 && nums[nums.length-1] == 7)){
    flag = true;
    }
    }
    return flag;
    }

    ReplyDelete
  5. public boolean has77(int[] nums) {
    for(int i=1;i<nums.length;i++){
    if(nums[i]==7 && nums[i-1]==7){
    return true;
    }else if(i<nums.length-1 && nums[i-1]==7 && nums[i]!=7 && nums[i+1]==7){
    return true;
    }
    }
    return false;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact