leetCode筆記--(1)
陪朋友刷題,記錄下。
1.
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won‘t be any divide by zero operation.
Q1. memcmp的誤用引發的內存堆棧溢出,可能由於編譯器的差別,本地OK,valgrind ok,但是遠端ERROR。
修復用strcmp,按字節比,直到1個到尾。
Q2. 二級指針的運用
char* acSrc[5] = {"2", "1", "+", "3", "*"};
char** ppTcSrc = NULL;
ppTcSrc = acSrc;
取“2”, “1” 這些成員,原先取 *ppTcSrc + 0, *ppTcSrc + 1
(gdb) n
140 return 0;
(gdb) p *ppTcSrc
$1 = 0x400bcb "2"
(gdb) p *ppTcSrc + 1
$2 = 0x400bcc ""
(gdb) p *ppTcSrc + 2
$3 = 0x400bcd "1"
(gdb) p *ppTcSrc + 3
$4 = 0x400bce ""
(gdb) p *ppTcSrc + 4
$5 = 0x400bcf "3"
(gdb) p *ppTcSrc + 5
$6 = 0x400bd0 ""
(gdb) p *ppTcSrc + 6
$7 = 0x400bd1 "%s "
本意是ppTcSrc[0], ppTcSc[1]. ... 也可以寫成*(ppTcSrc), *(ppTcSrc + 1)
$10 = 0x400ba0 "+"
(gdb) p ppTcSc[2]
No symbol "ppTcSc" in current context.
(gdb) p *(ppTcSrc + 2)
$11 = 0x400ba0 "+"
(gdb) p ppTcSrc[2]
$12 = 0x400ba0 "+"
## 還是要註意下, ppTcSrc 的類型是char*, 想下他的指向,他的自加是什麽意思。
2.
leetcode 7:
Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Q1:
AddressSanitizer: heap-buffer-overflow on address 0x602000000298 at pc 0x7f6c0babb79b bp 0x7ffdfb3aca30 sp 0x7ffdfb3ac1e0
原因分析:
memcmp 的S使用,可能是編譯器差距,本地OK。
解決方法:memcmp -> strncmp
3.405. Convert a Number to Hexadecimal
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character ‘0‘; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
-- 這個做的很開心,雖然折騰了下,但是還是搞定了。^_^
Q1:
# 負數問題
負數是有符號的,當想要轉成字符串,需要先轉成無符號的
# 補碼問題
負數,計算機用補碼表示。
$15 = -1
(gdb) p /x iRh
$16 = 0xffffffff
(gdb) p /x iRh>>4
$17 = 0xffffffff
# 值範圍
unsigned int 0~4294967295
int 2147483648~2147483647
unsigned long 0~4294967295
long 2147483648~2147483647
long long的最大值:9223372036854775807
long long的最小值:-9223372036854775808
unsigned long long的最大值:1844674407370955161
__int64的最大值:9223372036854775807
__int64的最小值:-9223372036854775808
unsigned __int64的最大值:18446744073709551615
# -2147483648的補碼
if (num == -2147483648) return 0xFFFFFFFF80000000;
git 地址:
https://github.com/HellsingAshen/Myleetcode-cn
leetCode筆記--(1)