본문 바로가기

코딩테스트/Coding Bat

[코딩뱃] [자바] Warmup - 1단계 : loneTeen 문제

728x90
728x90

https://codingbat.com/prob/p165701

 

CodingBat Java Warmup-1 loneTeen

We'll say that a number is "teen" if it is in the range 13..19 inclusive. Given 2 int values, return true if one or the other is teen, but not both.loneTeen(13, 99) → trueloneTeen(21, 19) → trueloneTeen(13, 13) → falseGo...Save, Compile, Run (ctrl-en

codingbat.com



= 문제 번역 =

숫자가 13..19(포함) 범위에 있으면 숫자가 "10대"라고 합니다. 

2개의 int 값이 주어지면 둘 중 하나가 십대일 때는 true를 반환한다.

int 값 둘 다 십대이면 반환한다.

 

 

= 문제푸는 팁 =

아래에 위치한 true및 false값을 참고해서 문제를 풀어도 좋다.

 

 

= 해설 =

< 1 >

public boolean loneTeen(int a, int b) {
  boolean aa = (a >= 13 && a <= 19);
  boolean bb = (b >= 13 && b <= 19);
  
  if((aa && !bb) || (!aa && bb))return true;
  else return false;
}

< 2 >
public boolean loneTeen(int a, int b) {
  // Store teen-ness in boolean local vars first. Boolean local
  // vars like this are a little rare, but here they work great.
  boolean aTeen = (a >= 13 && a <= 19);
  boolean bTeen = (b >= 13 && b <= 19);
  
  return (aTeen && !bTeen) || (!aTeen && bTeen);
  // Translation: one or the other, but not both.
  // Alternately could use the Java xor operator, but it's obscure.
}

728x90