본문 바로가기

알고리즘/[알고리즘] 코플릿

변수 타입 문자열

#Convert To Char

숫자(int) 하나를 입력받아 알맞은 문자(char)를 리턴하는 문제

    public class Solution { 
	public char convertToChar(int num) {
    char result;
    
    // TODO: 여기에 코드를 작성합니다.
		result = Character.forDigit(num, 10);
        
    return result;
    	}
     }
Character.forDigit() method를 사용하면 된다.

	public class IntToCharExample5{  
	public static void main(String args[]){  
	int REDIX=10;
    //redix 10 is for decimal number, for hexa use redix 16  
	int a=1;    
	
    char c=Character.forDigit(a,REDIX);    
	
    System.out.println(c);   
	}}  
   [link](https://www.javatpoint.com/java-int-to-char)
   위 예시와 같이 코드를 입력하면 int형인 a가 char형으로 바뀌어 1로 출력된다.
   Output : 1
   
##    #ComputeAverageLengthOfWords2
#### 두 단어를 입력받아 두 단어의 평균 길이를 내림하여 리턴해야 합니다.

	public class Solution { 
	public int computeAverageLengthOfWords2(String word1, String word2) {
    
    // TODO;
		double averageLength = (word1.length() + word2.length()) /2;
		return (int)Math.floor(averageLength);
		
        }
	}	
자바에서의 내림 연산은 Math.floor()를 사용한다.
처음 제출했던 코드

			return Math.floor((word1.length() + word2.length()) / 2);
1. averageLength로 두 단어의 평균 길이 객체를 생성할 생각을 못했다.
2. double 실수형으로 만들 생각을 못했다. 
3. 값 return 할때도 int형으로 return 할 생각 못함.

## #compareOnlyAlphabet
#### 두 개의 문자열을 입력받아 대소문자를 구분하지 않고(case insensitive) 서로 같은지 여부를 리턴해야 합니다.
처음 제출한 코드

	public class Solution { 
	public boolean compareOnlyAlphabet(String str1, String str2) {
    // TODO:
    
		return str1.upperCase(equals.str2.upperCase);
        
		} 
	}
1. boolean 타입 그러니까 true or false 형으로 출력되어야 한다는 조건때문에 equals를 썼는데 upperCase쓰고 바로 .equals를 써도 되는지 몰랐다.

	String a = "Man";
	int b = 0 ;
	
    // 자바는 String을 비교할 때 equal()을 이용합니다.
	// 그 이유는 String은 다른 자료형과 다른 문자열 자료형이기 때문입니다. 
	
    if(e.equals"Man")) {
	System.our.println("남자입니다.");
}

2. .upperCase X -> .toupperCase O

Reference Code 
	
    return str1.toLowerCase().equals(str2.toLowerCase());
    

 

'알고리즘 > [알고리즘] 코플릿' 카테고리의 다른 글

조건문  (1) 2022.09.23
반복문  (0) 2022.09.23
Collection  (0) 2022.09.23
재귀  (0) 2022.09.23
자료구조 Stack Queue Graph Tree DFS/BFS  (1) 2022.09.23