728x90
🍯 대소문자 구분 없이 문자 찾기
TIP ) 찾고자하는 문자/ 찾을 문자열을 모두 UpperCase 혹은 LowerCase로 맞춰준다
Example
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input1 = sc.next(); // Abstract
char input2 = sc.next().charAt(0); // a
input1= input1.toUpperCase(); // 전체 대문자 만들어주기 -> ABSTRACT
input2= Character.toUpperCase(input2); // 문자를 대문자로 만들기 -> A
int answer =0;
for(char x : input1.toCharArray()){ // 문자 배열 생성 후 for each문
if(input2 == x) answer++;
}
System.out.println(answer);
}
}
🍯 대문자는 소문자, 소문자는 대문자로
TIP ) Character 클래스를 이용하자!
사용할 메서드 ) isUpperCase / isLowerCase / toUpperCase / toLowerCase
Example
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input1 = sc.next();
String answer = ""; // 문자를 문자열에 저장하기 위한 공간
for(char x : input1.toCharArray()){
if(Character.isUpperCase(x)){ // x는 대문자인가?
answer += Character.toLowerCase(x); // 대문자라면 소문자로
}else{
answer += Character.toUpperCase(x);
}
}
System.out.println(answer);
}
}
🍯 대소문자 구분 없이 문자열 비교
TIP ) equals는 대소문자를 구분하기에 equalsIgnoreCase() 메서드 사용
사용할 메서드 ) equalsIgnoreCase()
Example
public class StringComparisonExample {
public static void main(String[] args) {
// 대소문자를 구분하는 비교
String str1 = "Hello";
String str2 = "hello";
if (str1.equals(str2)) {
System.out.println("두 문자열은 대소문자를 구분하여 동일합니다.");
} else {
System.out.println("두 문자열은 대소문자를 구분하여 다릅니다.");
}
// 대소문자를 구분하지 않는 비교
if (str1.equalsIgnoreCase(str2)) {
System.out.println("두 문자열은 대소문자를 구분하지 않고 동일합니다.");
} else {
System.out.println("두 문자열은 대소문자를 구분하지 않고 다릅니다.");
}
}
}
// 출력값
두 문자열은 대소문자를 구분하여 다릅니다.
두 문자열은 대소문자를 구분하지 않고 동일합니다.
🍯 최댓값 구하기
TIP ) MIN_VALUE 를 통해 최솟값으로 초기화해주자
사용할 메서드 ) MIN_VALUE
Example
public class Test3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine(); // it is time to study
sc.close();
String answer = "";
int m = Integer.MIN_VALUE; // Integer에서 가장 작은 값으로 초기화 (=-2147483648)
String[] s = input.split(" "); // 공백 기준으로 분리하여 배열 리스트 생성
for(String x : s){
int len = x.length();
if(len > m){ // x의 길이가 최댓값보다 크다면
m = len; // 최댓값으로 할당
answer = x; // 해당하는 x를 answer 에 저장
}
}
System.out.println(answer);
}
}
🍯 특수문자 찾기
TIP ) Character.isAlphabetic이 알파벳인지를 찾기에 논리 부정 연산자 (!) 를 사용하자!
사용할 메서드 ) !Character.isAlphabetic()
Example
public class AlphabeticExample {
public static void main(String[] args) {
// 테스트할 문자열
String testString = "Hello123";
// 문자열을 문자 배열로 변환
char[] charArray = testString.toCharArray();
// 각 문자가 알파벳인지 확인하고 결과 출력
for (char ch : charArray) {
if (!Character.isAlphabetic(ch)) {
System.out.println(ch + "는 알파벳이 아닙니다.");
} else {
System.out.println(ch + "는 알파벳입니다.");
}
}
}
}
🍯 소수 판별하기 1
TIP ) 가장 간단한 방식은 약수가 있는지 확인한다. 약수가 없다면 소수다
Example
public class PrimeExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("숫자를 입력하세요: ");
int num = sc.nextInt();
if (isPrime(num)) {
System.out.println(num + "은(는) 소수입니다.");
} else {
System.out.println(num + "은(는) 소수가 아닙니다.");
}
}
// 주어진 숫자가 소수인지 여부를 판별하는 메서드
public static boolean isPrime(int num){
if(num < 2) return false; // 0과 1은 소수가 아니다
for(int i=2; i<num; i++){
if(num % i == 0) return false; // num 이 어떠한 수로 나누어 떨어진다면 소수가 아니다
}
return true;
}
}
🍯 소수 판별하기 2
TIP ) 효율적인 알고리즘인 에라토스테네스 체 를사용한다
Example
import java.util.Arrays;
public class SieveOfEratosthenesExample {
// 에라토스테네스의 체를 사용하여 주어진 범위 내의 소수를 찾는 메소드
public static boolean[] sieveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false; // 0과 1은 소수가 아님
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
return isPrime;
}
public static void main(String[] args) {
int n = 30; // 30 이하의 소수를 찾는 예시
boolean[] primes = sieveOfEratosthenes(n);
System.out.println("에라토스테네스의 체를 사용하여 " + n + " 이하의 소수 찾기:");
for (int i = 2; i <= n; i++) {
if (primes[i]) {
System.out.print(i + " ");
}
}
}
}
🍯 배열 복사하기1
TIP ) Arrays.copyOf(복사할 배열, 배열의 크기);
Example
int[] originalArray = {1, 2, 3, 4, 5};
int[] newArray = Arrays.copyOf(originalArray, 3);
// 출력값
[1,2,3]
🍯 배열 복사하기2
TIP ) Arrays.copyOfRange(복사할 배열, 처음 인덱스, 끝 인덱스);
주의할 점! copyOfRange(arr, 1, 3); 이면 인덱스 1번부터 2번까지의 값이 복사가 된다.
끝 인덱스 미포함 ✨✨
Example
int[] originalArray = {1, 2, 3, 4, 5};
int[] subArray = Arrays.copyOfRange(originalArray, 1, 3);
//출력값
[2, 3]
🍯 숫자 뒤집기
방식 1) 자바 코드만을 이용하여 뒤집기
방식 2) StringBuilder() 의 reverse() 메서드 사용하여 뒤집기
Example
import java.util.Scanner;
public class ReverseNum1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int result = 0;
while(input !=0) {
result = result * 10 + input % 10; // 나머지 저장
input /= 10; // 저장된 수를 제외한 수만 남겨두기
}
System.out.println(result);
}
}
꿀 TIP)
result = result * 10 + input % 10
input /= 10;
import java.util.Scanner;
public class ReverseNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
StringBuilder sb = new StringBuilder(input);
int answer = Integer.valueOf(sb.reverse().toString());
System.out.println(answer);
}
}
StringBuilder 생성 후 reverse() 메서드 사용 -> String으로 형변환 -> int로 형변환
계속 추가될 예정입니다 : )
728x90
'Algorithm' 카테고리의 다른 글
[inflearn] 뒤집은 소수 (1) | 2024.01.10 |
---|---|
[inflearn] 피보나치 수열 (0) | 2024.01.10 |
✨ 알고리즘 관련 기초 자바 문법 (1) | 2024.01.01 |
[프로그래머스] (181916) 주사위 게임 3 (0) | 2023.12.29 |
[프로그래머스] (181913) 문자열 여러 번 뒤집기 (0) | 2023.12.28 |