1 Multiply Strings
Given numbers represented as strings, return multiplication of the numbers as a string. Note:the numbers can be arbitrarily large and is non-negative.
The problem is actually to use the string to solve the multiplication of large numbers. In order to calculate the convenience of the first two sets of numbers flipped, the string into an integer using two cycles per-phase multiplication, the results are saved. Then bitwise solve the rounding problem.
stringMultiplystringNUM1,stringNUM2) {intFlag =0, len1 = Num1.length (), len2 = Num2.length (); Reverse (Num1.begin (), Num1.end ()); Reverse (Num2.begin (), Num2.end ()); vector<int>Mid (Len1 + len2,0);stringResult for(inti =0; i<len1; i++) { for(intj =0; j<len2; J + +) {intA = Num1[i]-' 0 ';intb = Num2[j]-' 0 '; Mid[i + j] + = A*b; } } for(intm =0; M<len1 + len2; m++) {intc = (Mid[m] + flag)%Ten; Flag = (Mid[m] + flag)/Ten; MID[M] = c; }intn = len1 + Len2-1; while(Mid[n] = =0) {n--;//Remove the element with the front 0}if(n<0)returnResult + =' 0 '; for(; n >=0; n--) {result + = (' 0 '+ mid[n]); }returnResult }
2 permutations
Given A collection of numbers, return all possible permutations. For example,[1,2,3] has the following permutations:
[1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
Before we have solved the nextpermutation problem, we can get the next permutation of a set of sets of numbers in ascending order, and then loop through the next arrangement until there is no solution, and we can obtain the entire permutation of this group of numbers. The method also solves the permutations Ii.
BOOLNextpermutation ( vector<int>& Nums) {BOOLflag=true;if(Nums.size () <2)return false;intI, K; for(i = nums.size ()-2; I >=0; I.)if(Nums[i] < nums[i+1]) Break; for(k = nums.size ()-1; K > i; --K)if(Nums[i] < nums[k]) Break;if(i<0) flag=false;if(I >=0) Swap (Nums[i], nums[k]); Reverse (Nums.begin () + i +1, Nums.end ());returnFlag } vector<vector<int>>Permute ( vector<int>& Nums) {sort (Nums.begin (), Nums.end ()); vector<vector<int> >ResBOOLflag=true; while(flag) {Res.push_back (nums); Flag=nextpermutation (Nums); }returnRes }
Leetcode's Medium collection (C + + implementation) VI