Fastest C# solution


  • 0
    D

    I created a Solution based on double-click's "Easiest JAVA Solution" but optimized it. It scored 100% :-) I think this is still readable as well. In this version, we check for validity. I can't stomach not checking for valid input (I have TODO to through ArgumentNullException) :-) I also prefer iterating the arrays differently. I think the procedure is more clearly exhibited that way. Finally, I am using quick converts and no need for StringBuilder. Feedback is welcome.


        class Solution {
    	bool IsValidNum(char[] num) {
    		for(int i=0; i < num.Length/2; i++) {
    			if(!Char.IsDigit(num[i]) || 
    			   !Char.IsDigit(num[num.Length - i - 1])) {
    				return false;
    			}
    		}
    		return num.Length > 0;
    	}
    
    	public string Multiply(string num1, string num2) {
    		string answer = String.Empty;
    		char[] left = num1.ToCharArray();
    		char[] right = num2.ToCharArray();
    
    		if(num1=="0" || num2=="0") {//x*0=0, for all x
    			answer = "0";
    		}
    		else if(IsValidNum(left) && IsValidNum(right)){
    			byte[] result = new byte[left.Length + right.Length];
    
    			int position = result.Length - left.Length;//seed the first position
    			for(int i=right.Length - 1; i>=0; i--) {
    				position+=left.Length - 1;
    				for(int j=left.Length - 1; j>=0; j--) {
    					result[position] += (byte)((left[j] - '0') * (right[i] - '0'));
    					result[position - 1] += (byte)(result[position] / 10);
    					result[position--] %= 10;
    				}
    			}
    
    			if(result[position]==0) {
    				position++;
    			}
    
    			char[] answerBuffer = new char[result.Length - position];
    			int k=0;
    			while(position < result.Length) {
    				answerBuffer[k++] = (char)(result[position++] + '0');
    			}
    			answer = new string(answerBuffer);
    		}
    
    		return answer;
    	}
    }

Log in to reply
 

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