Add String

  1. LC 415

  2. Followup 1: if String has ","

  3. Followup2: implement 斐波那契数列

Solution 2:

public class AddInteger {

    public static void main(String[] args)
    {
        String num1 = "456,111,111";
        String num2 = "123,999";
        // 456235110
        String res1 = addStrings(num1, num2);
        System.out.println(res1);
    }

    public static String addStrings(String num1, String num2) {
        
        int len1 = num1.length()-1;
        int len2 = num2.length()-1;
        
        int preSign = 0;
        StringBuilder sb = new StringBuilder();
        
        while(len1 >=0  && len2 >=0)
        {
            if(!isValid(num1.charAt(len1)))
            {
                len1--;
                continue;
            }
            if(!isValid(num1.charAt(len2)))
            {
                len2--;
                continue;
            }

            int current = (num1.charAt(len1)-'0') + (num2.charAt(len2) - '0') + preSign;
            if(current < 10)
            {
                sb.append(current);
                preSign = 0;
            }
            else
            {
                sb.append(current%10);
                preSign  = 1;
            }
            len1--;
            len2--;
        }
        
        while(len1 >= 0)
        {
            if(!isValid(num1.charAt(len1)))
            {
                len1--;
                continue;
            }

            int current = (num1.charAt(len1) - '0') + preSign;
            if(current < 10)
            {
                sb.append(current);
                preSign = 0;
            }
            else
            {
                sb.append(current%10);
                preSign  = 1;
            }
            len1--;
        }
        
        while(len2 >= 0)
        {
            if(!isValid(num1.charAt(len2)))
            {
                len2--;
                continue;
            }

            int current = (num2.charAt(len2) - '0') + preSign;
            if(current < 10)
            {
                sb.append(current);
                preSign = 0;
            }
            else
            {
                sb.append(current%10);
                preSign  = 1;
            }
            len2--;
        }
        
        if(preSign != 0)
        {
            sb.append(preSign);
        }
        
        return sb.reverse().toString();
        
    }

    public static boolean isValid(char c)
    {
        return Character.isDigit(c);
    }
    
}

Last updated