(1)Add Strings
Given two non-negative integers num1
andnum2
represented as string, return the sum ofnum1
andnum2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library orconvert the inputs to integer directly.
这道题实现的就是一个加法运算,其中需要考虑整数型与string字符串之间的转换。在考虑字符串转换到整数型时,可以使用“字符串-‘0’”的方法,简单快捷;在考虑整数型转换到字符串时,可以使用<string>文件里的to_string函数。
加法运算中,本位用模运算,进位用除法即可得到。
#include <string>
class Solution
{
public:
string addStrings(string num1, string num2)
{
int in=0;
string res="";
int i=num1.size();
int j=num2.size();
//从低位往高位加
while(i>0||j>0||in>0)
{
int sum=0;
if(i>0)
{
sum += num1[i]-'0';
i--;
}
if(j>0)
{
sum += num2[j]-'0';
j--;
}
in=sum/10;//进位
sum=sum%10;//确定该位的数
res=res+to_string(sum);//合并到string res中
}
//反转
reverse(res.begin(),res.end());
return res;
}
};
(2)Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
在这道题中,我们要满足二叉查找树的性质就必须根的左边均小于根,右边均大于根。有序递增数组中,我们可以取数组的中间值作为树根,可以使得这颗二叉树平衡,又分别从左右子树中取中间值作为根,由此不断取中间值,这就形成了一个递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
if(nums.size()==0)
return NULL;
else if(nums.size()==1)
{
TreeNode* root=new TreeNode(nums[0]);
return root;
}
else if(nums.size()>1)
{
int mid=nums.size()/2;
TreeNode* root=new TreeNode(nums[mid]);
vector<int> left(nums.begin(),nums.begin()+mid-1);
vector<int> right(nums.begin()+mid+1,nums.end());
sortedArrayToBST(left);
sortedArrayToBST(right);
return root;
}
}
};