力扣---2020.8.3

415. 字符串相加

字符串加法、链表加法以及二进制加法之类的都可以这么写

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder(); //可以换用stack,list等存储
        int len1 = num1.length()-1,len2 = num2.length()-1;
        int carry = 0;
        while(len1 >= 0 || len2 >= 0 || carry > 0){
            if(len1 >= 0)  carry += num1.charAt(len1--) - '0';
            if(len2 >= 0)  carry += num2.charAt(len2--) - '0';
            sb.append(carry%10);
            carry /= 10;
        }
        return sb.reverse().toString();
    }
}

剑指 Offer 56 - II. 数组中数字出现的次数 II

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int num : nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }

        for(int num : nums){
            if(map.get(num)==1){
                return num;
            }
        }
        return -1;
    }
}
class Solution {
    public int singleNumber(int[] nums) {
        int a = 0;
        int b = 0;
        for(int num : nums) {
        	a = (a ^ num) & ~b;
        	b = (b ^ num) & ~a;
        }
        return a;
    }
}
class Solution {
    public int singleNumber(int[] nums) {
        int[] counts = new int[32];
        for(int num : nums) {
            for(int j = 0; j < 32; j++) {
                counts[j] += num & 1;
                num >>>= 1;
            }
        }
        int res = 0, m = 3;
        for(int i = 0; i < 32; i++) {
            res <<= 1;
            res |= counts[31 - i] % m;
        }
        return res;
    }
}

剑指 Offer 24. 反转链表

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null){
            return head;
        }
        ListNode prev = null;
        ListNode curr = head;
        while(curr!=null){
            ListNode nextTmp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTmp;
        }
        return prev;
    }
}
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode nextTmp = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return nextTmp; 
    }
}

你知道的越多,你不知道的越多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值