涉及题型:两数相加问题、大数溢出等
相加问题
- 根据题意定义
rs
的数据结构 - 判断是存储方式是正序还是逆序,如果是正序需要反转
- 比如 123 + 12 = 135是正序, 321 + 21 = 135是逆序
- 反转的方式:对于可以从后往前遍历的(如字符串、数组),直接从后往前遍历;不可以的(如链表)则先定义
reverse
反转整个结构
- 定义
进位carry = 0
,写循环条件while - 循环内部:
补0
、求和
、求进位 carry = sum / 10
、添加 sum % 10 到结果
、继续
- 正序的把结果再重新反转一下
字符串相加(正序)
public String addStrings(String num1, String num2) {StringBuilder sb = new StringBuilder();int i = num1.length()-1, j = num2.length()-1, carry = 0;//这里还要判断carry != 0 的情况!因为如果加起来是10的倍数,不判断carry是否为0 就不进位了while(i >= 0 || j >= 0 || carry != 0){ //🐖是>=0!//如果少位就补0int n1 = i >= 0 ? num1.charAt(i) - '0':0;//🐖是>=0!int n2 = j >= 0 ? num2.charAt(j) - '0':0;int sum = n1 + n2 + carry;carry = sum / 10;sb.append(sum % 10);j--;i--;}sb.reverse();return sb.toString() ;
}
链表相加(逆序)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {//1. 定义rsListNode rs = new ListNode();ListNode dummyHead = rs;//2. 逆序,无需反转; 3. 循环条件链表不为空int carry = 0;while(l1 != null || l2 != null || carry != 0){// 补0int n1 = l1 != null ? l1.val : 0;int n2 = l2 != null ? l2.val : 0;// 求和int sum = n1 + n2 + carry;// 求进位carry = sum / 10;// 添加到结果ListNode tmp = new ListNode(sum%10);rs.next = tmp;// 继续rs = rs.next;l1 = l1 != null ? l1.next:null;l2 = l2 != null ? l2.next:null;}return dummyHead.next;
}
链表相加(正序)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {l1 = reverseList(l1);l2 = reverseList(l2);ListNode rs = new ListNode();ListNode dummyHead = rs;int carry = 0;while(l1 != null || l2 != null || carry != 0){int n1 = l1 != null ? l1.val : 0;int n2 = l2 != null ? l2.val : 0;int sum = n1 + n2 + carry;carry = sum / 10;ListNode tmp = new ListNode(sum%10);rs.next = tmp;rs = rs.next;l1 = l1 != null ? l1.next : null;l2 = l2 != null ? l2.next : null;}return reverseList(dummyHead.next);
}
ListNode reverseList(ListNode head){ListNode cur = head;ListNode pre = null;while(cur != null){ListNode tmp = cur.next;cur.next = pre;pre = cur;cur = tmp;}return pre;
}
大数溢出
- 定义
boundry = Integer.MAX_VALUE / 10;
,也就是214748364 - 取
tmp
- 判断当前
rs
是否超出boundry 或 等于boundry(等于的话要看最后一位tmp
) rs = rs * 10 + tmp
整数反转
public int reverse(int x) {int rs = 0;int boundry = Integer.MAX_VALUE / 10;//这里要考虑负数的情况所以要!=0 而不是 > 0while(x != 0){int tmp = x%10;//判断是否大于最大的32位整数if(rs > boundry || (rs == boundry && tmp > 7)) return 0;if(rs < -boundry || (rs == -boundry && tmp < -8)) return 0;rs = rs*10 + tmp;x /= 10;}return rs;
}
字符串转整数(atoi)
public int myAtoi(String s) {int n = s.length();if(n == 0) return 0; //🐖这个判断不可少int i = 0, rs = 0, sign = 1, boundry = Integer.MAX_VALUE / 10; //去除首部空格while (s.charAt(i) == ' ') {if (i + 1 == n) return rs; i++;}//首位是-号,更改符号位if (s.charAt(i) == '-') {sign = -1;i++;} //首位是+号,直接i++else if (s.charAt(i) == '+') i++;for (int j = i; j < n; j++) {char c = s.charAt(j); //取tmpif (c > '9' || c < '0') //如果c不是数字字符 跳出break;//用一个符号位sign的正负可判断两种越界情况if (rs > boundry || (rs == boundry && c > '7')) {return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;}rs = rs * 10 + (c - '0');}return rs * sign; //返回的要*一个符号位!!
}