【leetcode】【Easy】【389. Find the Difference】【string】【bit manipulation】

problem link


code: code1和code3效率比较高。

code1:将string变为char数组比第二种直接操作string使用charAt方法要快很多

public class Solution {
    public char findTheDifference(String s, String t) {
        int sumS=0;
        int sumT=0;
        int i=0;
        char[] charS=s.toCharArray();
        char[] charT=t.toCharArray();
        for(;i<s.length();i++){
            sumS+=(int)charS[i];
            sumT+=(int)charT[i];
        }
        sumT+=(int)charT[i];
        return (char)(sumT-sumS);
    }
}

code2:

public class Solution {
    public char findTheDifference(String s, String t) {
        int sumS=0;
        int sumT=0;
        int i=0;
        for(;i<s.length();i++){
            sumS+=(int)s.charAt(i);
            sumT+=(int)t.charAt(i);
        }
        sumT+=t.charAt(i);
        return (char)(sumT-sumS);
    }
}
code3:效率较高的一种解法。位操作, 异或是经常用到的(相同为0,相异为1,与0异或为本身)

public class Solution {
    public char findTheDifference(String s, String t) {
	int n = t.length();
	char c = t.charAt(n - 1);
	for (int i = 0; i < n - 1; ++i) {
		c ^= s.charAt(i);
		c ^= t.charAt(i);
	}
	return c;
}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值