22. 자릿수 더하기
https://programmers.co.kr/learn/courses/30/lessons/12931?language=java
[풀이에 필요한 조건]
몇자리의 숫자인지 판독하기 위해 log함수를 사용.
(int)Math.log10(n)+1
10의 제곱근을 나타낼 Math.pow(double a, double b)을 통해
구하려고 하는 자리수보다 한자리 높은 10^자리수+1 로 나머지 계산,
뒷자리를 떼어내기 위해 동일한 10^자리수 로 나눠줌.
[해답]
class Solution {
public int solution(int n) {
int answer = 0;
int n_len = (int)Math.log10(n)+1;
for(int i=0;i<n_len;i++){
//123 %10 =3 /1 = 3
//123 %100 = 23 /10 = 2.3
//123 %1000 = 123 / 100 = 1.23
answer += (n%Math.pow((double)10,(double)i+1))/Math.pow((double)10,(double)i);
}
return answer;
}
}
import java.util.*;
class Solution {
public int solution(int n) {
int answer = 0;
int n_len = (int)Math.log10(n)+1;
for(int i=0;i<n_len;i++){
//123 %10 =3 /1 = 3
//123 %100 = 23 /10 = 2.3
//123 %1000 = 123 / 100 = 1.23
answer += (n%Math.pow((double)10,(double)i+1))/Math.pow((double)10,(double)i);
}
return answer;
}
}
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
int n=123;
//int n=987;
int result = sol.solution(n);
}
}
24. 정수 내림차순으로 배치하기
[풀이에 필요한 조건]
[해답]
import java.util.*;
class Solution {
public long solution(long n) {
long answer = 0;
String n_str = String.valueOf(n);
ArrayList<Character> n_list = new ArrayList<>();
String answer_str = "";
for(int i=0;i<n_str.length();i++){
n_list.add(n_str.charAt(i));
}
Collections.sort(n_list, Collections.reverseOrder());
for(int j=0;j<n_list.size();j++){
answer_str += Character.getNumericValue(n_list.get(j));
}
answer = Long.parseLong(answer_str);
return answer;
}
}
import java.util.*;
class Solution {
public long solution(long n) {
long answer = 0;
String n_str = String.valueOf(n);
ArrayList<Character> n_list = new ArrayList<>();
String answer_str = "";
for(int i=0;i<n_str.length();i++){
n_list.add(n_str.charAt(i));
}
Collections.sort(n_list, Collections.reverseOrder());
for(int j=0;j<n_list.size();j++){
answer_str += Character.getNumericValue(n_list.get(j));
}
answer = Long.parseLong(answer_str);
return answer;
}
}
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
long n = 799999999;
long result = sol.solution(n);
System.out.println(result);
}
}
25. 정수 제곱근 판별
[풀이에 필요한 조건]
n 값의 제곱근을 구하는 함수 Math.sqrt(n)을 long 값으로 저장.
(기본 형이 double 이기 때문에 차후 오류가 발생할 수 있음)
제곱근의 제곱과( Math.pow(sqrt_n,2) ) n값이 동일하다면,
제곱근에 1을 더해주고 제곱한 값을 출력값에 저장.
다른 경우 출력 기본값인 -1을 반환.
[해답]
저장이 날아가서 main 코드는 기재하지 않음.
class Solution {
public long solution(long n) {
long answer = -1;
long sqrt_n = (long)Math.sqrt(n);
if(Math.pow(sqrt_n,2)==n){
answer = (long)Math.pow(sqrt_n+1,2);
}
return answer;
}
}
26. 제일 작은 수 제거하기
[풀이에 필요한 조건]
배열 sort를 위해 arr 배열 clone.
clone 배열을 sort 하여 오름차순으로 정렬.
sort 된 배열의 맨 처음 데이터는 오름차순을 통해 최솟값으로 고정됨.
배열 0번 데이터를 최솟값으로 지정하고, 가변 list에 최솟값을 제외한 데이터를 저장.
list.size가 0이라면 보유중인 데이터가 없어 answer 길이는 1, 데이터는 -1로 저장.
이 외의 경우에는 answer 배열로 list의 데이터를 저장함.
[해답]
저장오류로 자바코드 없음.
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int[] answer = {};
int[] temp = arr.clone();
Arrays.sort(temp);
int minNum=temp[0];
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<arr.length;i++){
if(arr[i]!=minNum){
list.add(arr[i]);
}
}
if(list.size()==0){
answer = new int[1];
answer[0] = -1;
}
else{
answer = new int[list.size()];
for(int i=0;i<list.size();i++){
answer[i]=list.get(i);
}
}
return answer;
}
}
28. 하샤드 수
https://programmers.co.kr/learn/courses/30/lessons/12947
[풀이에 필요한 조건]
x 를 문자열로 받아오기 위해 String.valueOf(x) 를 사용함.
문자열에서 특정 문자의 값을 숫자로 받아오기 위해 Character.getNumberValue(x_str.charAt(i)) 로 tmp에 값을 저장.
문자열의 숫자 값을 모두 sum으로 더해주고, sum으로 x를 나누었을 때 나머지가 0이 나오는지 확인해줌.
x%sum != 0 이라면 하샤드 수가 아니게 되어 false 출력.
[해답]
class Solution {
public boolean solution(int x) {
boolean answer = true;
String x_str = String.valueOf(x);
int tmp = 0;
//System.out.println("x_str = "+x_str);
int sum =0;
for(int i=0; i<x_str.length() ; i++){
//System.out.println("x_str.charAt("+i+") = "+x_str.charAt(i));
tmp = Character.getNumericValue(x_str.charAt(i));
//System.out.println("tmp = "+tmp);
sum += tmp;
//System.out.println("sum = "+sum);
}
if(x%sum != 0){
answer = false;
}
return answer;
}
}
import java.util.ArrayList;
class Solution {
public boolean solution(int x) {
boolean answer = true;
String x_str = String.valueOf(x);
int tmp = 0;
//System.out.println("x_str = "+x_str);
int sum =0;
for(int i=0; i<x_str.length() ; i++){
//System.out.println("x_str.charAt("+i+") = "+x_str.charAt(i));
tmp = Character.getNumericValue(x_str.charAt(i));
//System.out.println("tmp = "+tmp);
sum += tmp;
//System.out.println("sum = "+sum);
}
if(x%sum != 0){
answer = false;
}
return answer;
}
}
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
int x = 10;
boolean result = sol.solution(x);
System.out.println(result);
}
}
29. 3진법 뒤집기
https://programmers.co.kr/learn/courses/30/lessons/68935
[풀이에 필요한 조건]
3진법으로 45를 나타내면 27+18 로 1200이다.
3^4 | 3^3 | 3^2 | 3^1 | 3^0 |
81 | 27 | 9 | 3 | 1 |
0 | 1 | 2 | 0 | 0 |
위 풀이는 계산이 많아지기 때문에, 나머지로 연산하여 계산하면 아래 표와 같다.
45/3 | 15/3 | 5/3 | 1/3 |
15 | 5 | 1 | 0 |
45%3 | 15%3 | 5%3 | 1%3 |
0 | 0 | 2 | 1 |
입력 받은 자연수를 3으로 나눈 값이 0보다 클 때,
나머지 값을 Arraylist에 순서대로 추가해주면 입력받은 자연수의 3진법 반전상태가 된다.
반전상태의 3진수를 계산하기 위해 반복마다 제곱이 하나씩 빠지도록 계산되는 변수를 생성.
double multiple = Math.pow(3,squared-1);
squared -= 1;
list의 데이터와 계산, 출력값으로 추가.
answer += arr.get(i)*(int)multiple;
[해답]
import java.util.*;
class Solution {
public int solution(int n) {
int answer=0;
ArrayList<Integer> arr = new ArrayList<>();
while(n>0){
arr.add(n%3);
n /= 3;
}
int squared = arr.size();
for(int i=0;i<arr.size();i++){
double multiple = Math.pow(3,squared-1);
squared -= 1;
answer += arr.get(i)*(int)multiple;
//System.out.println("arr.get("+i+") = "+ arr.get(i) +" * (int)multiple ="+ (int)multiple+" = "+answer);
}
return answer;
}
}
import java.util.*;
class Solution {
public int solution(int n) {
int answer=0;
ArrayList<Integer> arr = new ArrayList<>();
while(n>0){
arr.add(n%3);
n /= 3;
}
int squared = arr.size();
for(int i=0;i<arr.size();i++){
double multiple = Math.pow(3,squared-1);
squared -= 1;
answer += arr.get(i)*(int)multiple;
//System.out.println("arr.get("+i+") = "+ arr.get(i) +" * (int)multiple ="+ (int)multiple+" = "+answer);
}
return answer;
}
}
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
int n = 45;
int result = sol.solution(n);
System.out.println("결과값 : " + result);
}
}
30. 최소직사각형
[풀이에 필요한 조건]
가로 길이와 세로의 길이가 다르지만, 90도 회전하여 바꿀 수 있는 조건.
긴 모서리를 2차원 배열의 첫번째에 배치, 짧은 모서리를 두번째에 배치하도록 변경하여 리스트에 각각 저장.
for(int i=0;i<sizes.length;i++) {
if(sizes[i][0] < sizes[i][1]){
tmp[i][0] = sizes[i][1];
tmp[i][1] = sizes[i][0];
sizes[i][0] = tmp[i][0];
sizes[i][1] = tmp[i][1];
compare_w.add(sizes[i][0]);
compare_h.add(sizes[i][1]);
}
else{
compare_w.add(sizes[i][0]);
compare_h.add(sizes[i][1]);
}
}
작성된 ArrayList를 내림차순으로 정렬.
Collections.sort(compare_w, Collections.reverseOrder());
Collections.sort(compare_h, Collections.reverseOrder());
리스트의 첫번째 수치들의 곱을 한 값을 리턴하면 가장 큰 명함이 들어갈 수 있는 사이즈가 계산됨.
answer = compare_h.get(0)*compare_w.get(0);
[해답]
import java.util.*;
class Solution {
public int solution(int[][] sizes) {
int answer = 0;
int[][] tmp = new int[sizes.length][sizes.length];
ArrayList<Integer> compare_w = new ArrayList<>();
ArrayList<Integer> compare_h = new ArrayList<>();
for(int i=0;i<sizes.length;i++) {
if(sizes[i][0] < sizes[i][1]){
tmp[i][0] = sizes[i][1];
tmp[i][1] = sizes[i][0];
sizes[i][0] = tmp[i][0];
sizes[i][1] = tmp[i][1];
compare_w.add(sizes[i][0]);
compare_h.add(sizes[i][1]);
}
else{
compare_w.add(sizes[i][0]);
compare_h.add(sizes[i][1]);
}
}
Collections.sort(compare_w, Collections.reverseOrder());
Collections.sort(compare_h, Collections.reverseOrder());
answer = compare_h.get(0)*compare_w.get(0);
return answer;
}
}
import java.util.*;
class Solution {
public int solution(int[][] sizes) {
int answer = 0;
int[][] tmp = new int[sizes.length][sizes.length];
ArrayList<Integer> compare_w = new ArrayList<>();
ArrayList<Integer> compare_h = new ArrayList<>();
for(int i=0;i<sizes.length;i++) {
if(sizes[i][0] < sizes[i][1]){
//System.out.println("기존 sizes["+i+"][0] = " + sizes[i][0] +" / sizes["+i+"][1] = " + sizes[i][1]);
//System.out.println("전 tmp["+i+"][0] = " + tmp[i][0] +" / tmp["+i+"][1] = " + tmp[i][1]);
tmp[i][0] = sizes[i][1];
tmp[i][1] = sizes[i][0];
//System.out.println("후 tmp["+i+"][0] = " + tmp[i][0] +" / tmp["+i+"][1] = " + tmp[i][1]);
sizes[i][0] = tmp[i][0];
sizes[i][1] = tmp[i][1];
//System.out.println("변경 sizes["+i+"][0] = " + sizes[i][0] +" / sizes["+i+"][1] = " + sizes[i][1]);
compare_w.add(sizes[i][0]);
compare_h.add(sizes[i][1]);
}
else{
compare_w.add(sizes[i][0]);
compare_h.add(sizes[i][1]);
}
}
Collections.sort(compare_w, Collections.reverseOrder());
Collections.sort(compare_h, Collections.reverseOrder());
//for(int j=0;j<compare_w.size();j++){
// System.out.println("compare_w.get("+j+") =" + compare_w.get(j));
// System.out.println("compare_h.get("+j+") =" + compare_h.get(j));
//}
answer = compare_h.get(0)*compare_w.get(0);
//System.out.println(answer);
return answer;
}
}
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
int[][] sizes = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
int result = sol.solution(sizes);
}
}
//가져온 풀이
import java.util.*;
class Solution {
public int solution(int[][] sizes) {
return Arrays.stream(sizes).reduce((a, b) -> new int[]{
Math.max(Math.max(a[0], a[1]), Math.max(b[0], b[1])), Math.max(Math.min(a[0], a[1]), Math.min(b[0], b[1]))
}).map(it -> it[0] * it[1]).get();
}
}