-- 事务 A
BEGIN;
SELECT balance FROM user WHERE id=1; -- 结果 500
-- 事务 B
BEGIN;
UPDATE user SET balance=800 WHERE id=1;
COMMIT;
-- 事务 A
SELECT balance FROM user WHERE id=1; -- 结果仍为 500
COMMIT;
SELECT balance FROM user WHERE id=1; -- 结果 800
六、编程题
32 位有符号整数反转
java复制代码
public class ReverseInteger {
public int reverse(int x) {
int res = 0;
while (x != 0) {
// 弹出最后一位
int digit = x % 10;
x = x / 10;
// 预判溢出
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && digit > 7)) {
return 0;
}
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && digit < -8)) {
return 0;
}
// 拼接数字
res = res * 10 + digit;
}
return res;
}
// 测试用例
public static void main(String[] args) {
ReverseInteger solution = new ReverseInteger();
System.out.println(solution.reverse(123)); // 321
System.out.println(solution.reverse(-123)); // -321
System.out.println(solution.reverse(120)); // 21
System.out.println(solution.reverse(2147483647)); // 0
}
}
代码解释
弹出数字:x%10 取最后一位,x/10 去除最后一位(负数除法仍为负);
溢出预判:通过 res > MAX/10 或 res < MIN/10 提前判断,避免直接溢出;
拼接数字:无溢出则更新结果,循环至 x=0。
岛屿数量(Go BFS 版)
go复制代码
func numIslands(grid [][]byte) int {
if len(grid) == 0 {
return 0
}
count := 0
rows, cols := len(grid), len(grid[0])
dirs := [][]int{{-1,0}, {1,0}, {0,-1}, {0,1}} // 上下左右
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
if grid[i][j] == '1' {
count++
// BFS 队列
queue := [][]int{{i,j}}
grid[i][j] = '0' // 标记已访问
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
// 遍历四个方向
for _, dir := range dirs {
x, y := curr[0]+dir[0], curr[1]+dir[1]
if x >=0 && y >=0 && x < rows && y < cols && grid[x][y] == '1' {
queue = append(queue, []int{x,y})
grid[x][y] = '0'
}
}
}
}
}
}
return count
}