짬뽕얼큰하게의 맨땅에 헤딩 :: Sum of Digits of String After Convert

Leetcode Problem:

Summary

  • This problem involves converting a string into an integer by replacing each letter with its position in the alphabet, then transforming the integer by summing its digits repeatedly k times.

Approach

  • The approach used is to first convert the string into an integer by subtracting the ASCII value of 'a' from each character and adding 1
  • Then, the integer is transformed by summing its digits using a helper function
  • This process is repeated k times.

Complexity

  • O(n*k) where n is the length of the string and k is the number of transformations.

Explain

  • The solution code defines a class Solution with two methods: getSum and getLucky
  • The getSum method takes a string as input and returns the sum of its digits
  • The getLucky method takes a string and an integer as input and returns the resulting integer after performing the transformations
  • The getLucky method first converts the string into an integer, then repeatedly transforms the integer by summing its digits using the getSum method
  • The process is repeated k times, and the final result is returned.

Solution Code:


class Solution {
public:
    int getSum(string s){
        int sum = 0;
        for(int i = 0 ; i < s.size(); i++){
            sum += s[i] - '0';
        }
        return sum;
    }
    int getLucky(string s, int k) {
        string num = "";
        for(int i = 0 ; i < s.size(); i++){
            num += to_string(s[i] - 'a' + 1);
        }
        int transform;
        while(k--){
            transform = getSum(num);
            num = to_string(transform);
        }
        
        return transform;
    }
};

'알고리즘' 카테고리의 다른 글

Find Missing Observations  (0) 2025.02.11
Walking Robot Simulation  (0) 2025.02.11
Find the Student that Will Replace the Chalk  (0) 2025.02.11
Convert 1D Array Into 2D Array  (0) 2025.02.11
Path with Maximum Probability  (0) 2025.02.11
블로그 이미지

짬뽕얼큰하게

,