leetcode 随笔 Plus One & Add Binary --两道 leetcode 适合新手的题

今天这两题可以说是很基础了,比较适合新手,lz大概是从大一就听C++老师给我们推荐去leetcode上面刷刷题锻炼编程,当时基本上也就是刚会写hello world的水平吧,看着输入的vector真是一脸懵逼,因此就放弃了。其实当时的基础几乎等于0,大二之前也没有写过超过200行的程序。

到了大二下学习数据库,数据库老师又提起让我们没事刷刷leetcode,当时也有了一定的编程能力了,然后靠百度学会了vector,其实vector就是跟数组差不多的玩意,只不过老师上课没讲,第一个leetcode程序two sum还是用二重循环跑的,好像当时是超时了吧。后来看了discuss才学会了双指针跑过了。但是给lz的体验就很差了。

其实如果要是能从易到难还是可以培养自己的自信的,比如如下两题:

我感觉大二做这个难度的题还是很容易accept的

Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

这个题的意思是 给你一个数 返回 这个数+1的结果

只不过结果和这个数都是用vector存的

也就是说123 存成了[1,2,3] 然后 加1 返回结果 [1,2,4] 

class Solution {
public:
	vector<int> plusOne(vector<int>& digits) {
		int c = 1;
		for (int i = digits.size() - 1; i >= 0; i--)
		{
			if (c == 0) return digits;
			digits[i] += c;
			c = digits[i] / 10;
			digits[i] %= 10;
		}
        if(c)
		    digits.insert(digits.begin(), 1);
		return digits;
	}
};

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Add Binary

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
现在是变成了两个二进制数相加,跟上面那题差别不大,长度短的二进制数前面补0就行了。
class Solution {
public:
	string addBinary(string a, string b) {
		int c = 0, n, i;
		if (a.size() > b.size())
		{
			n = a.size();
			string s(n - b.size(), '0');
			b = s + b;
		}
		else
		{
			n = b.size();
			string s(n - a.size(), '0');
			a = s + a;
		}
		string f(n, '0');
		i = n - 1;
		for ( ; i>=0;i--)
		{
			int t = a[i] - '0' + b[i] - '0' + c;
			c = t / 2;
			f[i] += (t%2);
		}
		if (c)
			f.insert(f.begin(), '1');
		return f;
	}
};

猜你喜欢

转载自blog.csdn.net/Runner_of_nku/article/details/80070634