https://leetcode.com/problems/happy-number/description/

 

Happy Number - LeetCode

Can you solve this real interview question? Happy Number - Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: * Starting with any positive integer, replace the number by the sum of the squar

leetcode.com

 

주어진 조건을 만족하는지 체크하는 문제이다. 단순 수식 구현 문제로 문제에서 제시하는 조건들을 따라 해결해 나가면 된다. 숫자를 10의 자리 단위로 분해하여 제곱 해서 더해야 하므로 %, / 연산자를 써서 해결해 나가면 된다. 최종 조건인 1이 되는 경우 외에도 무한히 반복되는 경우로 4가 있었다. 이를 체크하기 위해 set을 이용하여 사이클 체크를 해주었다.

import java.util.*;  
  
public class Solution {  
    public boolean isHappy(int n) {  
        Set<Integer> set = new HashSet<>();  
  
        while(n > 1){  
            int sum = 0;  
            while(n > 0){  
                int mod = n % 10;  
                sum += mod * mod;  
                n = n / 10;  
            }  
  
            n = sum;  
            if(set.contains(n)) break;  
            set.add(n);  
        }  
  
        return n == 1;  
    }  
}

'Algolithm-Leetcode > Math & Geometry' 카테고리의 다른 글

Set Matrix Zeroes  (0) 2026.08.20
Spiral Matrix  (0) 2026.08.14
Rotate Image  (0) 2026.08.07

https://leetcode.com/problems/set-matrix-zeroes/description/

 

Set Matrix Zeroes - LeetCode

Can you solve this real interview question? Set Matrix Zeroes - Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place [https://en.wikipedia.org/wiki/In-place_algorithm].   Example 1: [https

leetcode.com

 

주어진 매트릭스에서 0이 존재하는 행과 열을 0으로 전부 변환시키는 문제이다. 별도의 배열을 완성하는게 아니라 기존의 매트릭스를 변환해야한다. 특정 좌표의 (r, c)에 0이 존재하면 해당 r행과 c열을 모두 변환하기에 이를 체크하기 위해 boolean 배열로 체크했다. 아래는 통과코드이다.

  public class Solution {  
  
    public void setZeroes(int[][] matrix) {  
  
        int m = matrix.length;  
        int n = matrix[0].length;  
        boolean[] checkRow = new boolean[m];  
        boolean[] checkCol = new boolean[n];  
  
        for(int i = 0; i < m; i++){  
            for(int j = 0; j < n; j++){  
                if(matrix[i][j] == 0){  
                    checkRow[i] = true;  
                    checkCol[j] = true;  
                }  
            }  
        }  
  
        for(int i = 0; i < m; i++){  
            for(int j = 0; j < n; j++){  
                if(checkRow[i] || checkCol[j]){  
                    matrix[i][j] = 0;  
                }  
            }  
        }  
    }  
  
}

'Algolithm-Leetcode > Math & Geometry' 카테고리의 다른 글

Happy Number  (0) 2026.08.23
Spiral Matrix  (0) 2026.08.14
Rotate Image  (0) 2026.08.07

https://leetcode.com/problems/spiral-matrix/

 

Spiral Matrix - LeetCode

Can you solve this real interview question? Spiral Matrix - Given an m x n matrix, return all elements of the matrix in spiral order.   Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg] Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Outpu

leetcode.com

 

주어진 매트릭스를 주어진 방식으로 안으로 순회하며 값을 리스트에 담아 리턴하는 문제이다.
행과 열의 방향을 배열로 하여 돌아갈 방향을 정해줄 수 있다.

    int[] dr = {0, 1, 0, -1};
    int[] dc = {1, 0, -1, 0};
    
    int dir = 0;
    int nextRow = curRow + dr[dir];
    int nextCol = curCol + dc[dir]; 

 

위와 같은 형식으로 dir의 값 0~3에 따라 다음 좌표의 행과 열을 이동할 수 있다. dr, dc 의 인덱스별 값에 따라 위치를 지정해줄 수 있으며 문제에서 주어진 방식으로 순서대로 회전하기 위해서 위 코드와 같은 순서로 배열의 값을 지정해주었다.

 

그 이후 회전하는 타이밍을 정해야 했다. 회전하는 타이밍은 벽에 막히거나 또는 다음 위치가 이미 방문할 위치일 경우이다. 이를 위해서 매트릭스의 범위와 visited 배열을 이용하여 체크해주었다. 아래는 해결한 전체 코드이다.

import java.util.*;  
  
public class Solution {  
  
    static int[] dr = {0, 1, 0, -1};  
    static int[] dc = {1, 0, -1, 0};  
    static boolean[][] visited;  
  
    public List<Integer> spiralOrder(int[][] matrix) {  
        List<Integer> answer = new ArrayList<>();  
  
        visited = new boolean[matrix.length][matrix[0].length];  
  
        int r = 0;  
        int c = 0;  
        int dir = 0;  
  
        while(isValidDirection(matrix, r, c)){  
            visited[r][c] = true;  
  
            answer.add(matrix[r][c]);  
            int nextr = r + dr[dir];  
            int nextc = c + dc[dir];  
            if(!isValidDirection(matrix, nextr, nextc)){  
                dir = (dir + 1) % 4; // 0 - 우, 1 - 하, 2 - 좌, 3 - 상  
                nextr = r + dr[dir];  
                nextc = c + dc[dir];  
            }  
  
            r = nextr;  
            c = nextc;  
        }  
  
        return answer;  
    }  
  
    private boolean isValidDirection(int[][] matrix, int r, int c){  
        return r >= 0 && r < matrix.length  
                && c >= 0 && c < matrix[0].length  
                && !visited[r][c];  
    }  
}

'Algolithm-Leetcode > Math & Geometry' 카테고리의 다른 글

Happy Number  (0) 2026.08.23
Set Matrix Zeroes  (0) 2026.08.20
Rotate Image  (0) 2026.08.07

https://leetcode.com/problems/rotate-image/description/

 

Rotate Image - LeetCode

Can you solve this real interview question? Rotate Image - You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place [https://en.wikipedia.org/wiki/In-place_algorithm], which m

leetcode.com

 

매개변수로 주어진 matrix를 90도 돌리는 문제이다. 이 때 별도의 2차원 배열을 사용하는 것이 아니라. 바로 주어진 matrix 배열을 변화시켜야 한다. void 속성의 메서드로 내부적으로 결과를 해결하는 것 같다.

 

별도의 배열을 사용할 수 없어서 처음에는 당황했으나 위에서 부터 한 row 씩 돌린다고 생각하며
해결했다. 2차원 배열은 일종의 사각형 형태이므로 상우하좌 순으로 돌아간다는 것을 생각하여
돌려주었다. 이때 각 4개의 방향을 임시 변수로 설정해주었다. 문제를 해결하고 나서 생각하니 temp 를 하나만 사용해도 될 수 있다는 것을 깨달았으나.

 

블로그에 올리기 위해서는 아래의 초기 코드가 이해를 쉽게 할 수 있다고 생각하여
최초에 풀었던 방식으로 코드를 가져왔다.

public class Solution {  
    public void rotate(int[][] matrix) {  
        int n = matrix.length - 1;  
        for(int i = 0; i <= n; i++){  
            // 4분면을 한번에 돌리므로 i row를 돌렸다는 것은 i, n-i 의 row와 col 을 해결한 것이므로  
            // j = i, j < n -i 조건으로 반복 처리하지 않게한다.  
            for(int j = i; j < n - i ; j++){  
                int temp1 = matrix[i][j];        // 상  
                int temp2 = matrix[j][n - i];    // 우  
                int temp3 = matrix[n - i][n - j];// 하  
                int temp4 = matrix[n - j][i];    // 좌  
  
                // 회전  
                matrix[i][j] = temp4;  
                matrix[j][n - i] = temp1;  
                matrix[n - i][n - j] = temp2;  
                matrix[n - j][i] = temp3;  
            }  
        }  
    }  
}

'Algolithm-Leetcode > Math & Geometry' 카테고리의 다른 글

Happy Number  (0) 2026.08.23
Set Matrix Zeroes  (0) 2026.08.20
Spiral Matrix  (0) 2026.08.14

+ Recent posts