C++ 3ms simple/clean code (no recursion)


  • 0
    class Solution {
        void combine( char & a1, char a2, char & a3 ){
            int tmp = a1-'0'+a2-'0'+a3-'0';
            a1 = (char) (tmp % 10+'0');
            a3 = (char) (tmp / 10+'0');
        }
        void combine( char & a1, char & a3 ){
            int tmp = a1-'0'+a3-'0';
            a1 = (char) (tmp % 10+'0');
            a3 = (char) (tmp / 10+'0');
        }
    public:
        string addStrings(string num1, string num2) {
            // To ensure longer numA.
    	    string & numA = num1.size() >= num2.size() ? num1 : num2;
    	    string & numB = num1.size() <  num2.size() ? num1 : num2;
            
            char carry = '0';
            for( int i1= numA.size()-1, i2=numB.size()-1; i1>=0 || i2>=0; i1--, i2--){
                if( i2 >=0 ) combine(numA[i1], numB[i2], carry);
                else         combine(numA[i1], carry);
            }
            if( carry != '0' ){
                string a(1,carry);
                numA = a+numA;
            }
            return numA;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.