LeetCode_2. Add Two Numbers
原题:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解析:复习一下链表,题目大意是将两个两个链表的数据加起来,然而这两个链表是倒着存放数字的。这就像小学数学的加法,若两对应数字相加大于等于10则进一位。因此思路比较简单,主要目的是复习链表用法。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l1_pos = l1;
ListNode* l2_pos = l2;
ListNode* result_pos =new ListNode(0);
ListNode* result = result_pos;
int extra = 0;
while(l1_pos || l2_pos || extra){
int a = 0, b = 0;
if(l1_pos != NULL){
a = l1_pos->val;
l1_pos = l1_pos->next;
}
if(l2_pos != NULL){
b = l2_pos->val;
l2_pos = l2_pos->next;
}
int sum = a + b + extra;
extra = sum / 10;
result_pos->next = new ListNode(sum % 10);
result_pos = result_pos->next;
}
return result->next;
}
};
感想:前几次提交都没有任何输出,最后发现是一开始初始result_pos = null,然后result = result_pos,可能result直接就置空了,所以后来改成了上述实现。
LeetCode_6. ZigZag Conversion
原题:The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P—-A—-H—-N
-A–P–L–S–I—I—G
—Y—–I——R
解析:就是将其string变成之字型排序,所以可以创建一个行数*字符串长度的二元数组,将数据填入其中,则最后逐行输出需要的字符。
class Solution {
public:
string convert(string s, int numRows) {
string result;
int size = s.size();
int row = 0,col = 0;
int tag = 1;//tag=1->add,tag=0->sub
vector<vector<char> > a(numRows,vector<char>(size,0));
for(int i = 0;i < size;i++){
a[row][col] = s[i];
if(numRows == 1);
else if(tag){
if(row + 1 == numRows - 1)tag = 0;
row ++;
}
else{
if(row - 1 == 0)tag = 1;
row--;
}
col++;
}
for(int i = 0;i < numRows;i++){
for(int j = 0;j < size;j++){
if(a[i][j] != 0)result += a[i][j];
}
}
return result;
}
};