Wednesday, March 3, 2021

Leetcode Everyday: 1323. Maximum 69 Number. Easy

public class Solution {
    public int Maximum69Number (int num) {
        
        var sNum = num.ToString();
        var foundAt = sNum.IndexOf('6');
                   
        if (foundAt >= 0) {
            return num +  (3 * (int)Math.Pow(10, sNum.Length - foundAt - 1));
        }
        
        return num;        
    }
}
Same speed as above (32ms), but uses less memory:
public class Solution {
    public int Maximum69Number (int num) {
    
            var add = 0;

            for (int temp = num, step = 1; temp > 0; temp /= 10, step *= 10) {
                if (temp % 10 == 6) {
                    add = step * 3;
                }
            }

            return num + add;
    }
}
Source: https://leetcode.com/problems/maximum-69-number/

No comments:

Post a Comment