Meta Interview Question

How would you multiply two strings: "123 * "45", without any casting.

Interview Answers

Anonymous

Aug 6, 2014

God damn these commentors are idiots..it clearly says that you cannot convert to an int and you paste pieces of memorized code where you are converting to int..smh

6

Anonymous

May 30, 2014

public String multiply(String one, String two) { char[] one_char; char[] two_char; int carry = 0; if(one.length() > two.length()){ one_char = one.toCharArray(); two_char = two.toCharArray(); } else{ one_char = two.toCharArray(); two_char = one.toCharArray(); } int[] result = new int[one_char.length + two_char.length]; for(int index = two_char.length - 1; index >= 0 ;index--){ for(int index2 = one_char.length - 1; index2 >= 0 ;index2--){ int value = ((one_char[index2] - '0') * (two_char[index] - '0')) + result[(index2 + index) + 1]; result[(index2 + index) + 1] = value % 10; carry = value / 10; result[(index2 + index)] += carry; } } return Arrays.toString(result); }

1

Anonymous

Aug 4, 2014

public static void main(String[] args) { String s1 = "4567"; String s2 = "1234"; int res = convertString2Int(s1) * convertString2Int(s2); System.out.println(res); } public static int convertString2Int(String s){ char []chs = s.toCharArray(); int n1 = 0; for(int i=0; i < chs.length ; i++){ n1 = n1 + (chs[i]-'0') * getPowerOf(10, chs.length-i); } return n1; } public static int getPowerOf(int num, int times){ int val = 1; for(int i =0; i

Anonymous

Nov 19, 2014

//Assumption +ve interger ... no sigh, no .,no float resut is within range of int int multiplicationWithoutCast(string str1,string str2) { int finalresult=0; if(str2.length() == 1) { int result=0; int intResult =0; int carry = 0; int j = 1; // used unsigned int i so infinite loop bcz never goes below zero for(int i=str1.length()-1; i>=0; i--,j=j*10) // u did j+10 first :/ { intResult = (str1[i] - '0' ) * (str2[0] -'0') + carry; //cout =0;i--,j=j*10) { finalresult = finalresult + multiplicationWithoutCast(str1,str2.substr(i,1)) * j; } return finalresult; } }

Anonymous

Mar 1, 2014

I tried many methods but was not successful or/and efficient

Anonymous

Mar 6, 2014

How about getting the ascii code for each character, substracting 48, then you would have each digit. Then you can multiply them?

Anonymous

Mar 17, 2014

1. Add using a loop. Or 2. Bitwise operation.

Anonymous

Apr 3, 2014

// C# static int StrToInt( string s ) { if( s == null ) return int.MinValue; int n = 0; for( int i = s.Length - 1; i >= 0; --i ) n = (n * 10) + (s[i] - '0'); return n; } static int MultiplyStrings( string s1, string s2 ) { int n1 = StrToInt( s1 ); int n2 = StrToInt( s2 ); return n1 * n2 ; }

1