C++ sum(t[i]) - sum(s[i]) to find the one different.


  • 0
    X
    class Solution {
    public:
        char findTheDifference(string s, string t) {
            if(s.length()==0) return t[0]; 
            if(s.length()==1) return (s[0]==t[0]) ? t[1] : t[0]; 
            
    /*=============================================================================
        V 1.1 : use t[i]-s[i] and transfer into ascii as char.
        Time: O(n), space: O(1)
    *///===========================================================================
            int find = 0; 
            for(int i = 0; i < t.length(); i++) find += t[i]; 
            for(int i = 0; i < s.length(); i++) find -= s[i]; 
            char rlt = find; 
            return rlt; 
            
    /*=============================================================================
        V 1.0 : use A^B^A = B to find the single one.
        Time: O(n), space: O(1)   BUG: '\x00' yet should be 'e'.
    *///===========================================================================
    /*        char find = s[0]^s[1];
            cout<<"find = "<<find<<endl; 
            for(int i = 2; i < s.length(); i++){
                find ^= s[i]; 
            }
            for(int i = 0; i < s.length(); i++){
                find ^= t[i]; 
            }
            return find; 
    */        
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.