`
junfeng_feng
  • 浏览: 19991 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

LeetCode interview Questions:Add binay

 
阅读更多

LeetCode interview Questions:Add binay

1.int之类的数可以使用small

2.直接在字符串使用二进制的加法

http://www.leetcode.com/onlinejudge 需要

class Solution {
public:
    int string_to_int(string str) {
        int result = 0;
        int level = 1;
        for(int i = str.length() - 1; i >=0 ; i--) {
            if (str[i] == '1') {
                result += level;
            }
            level <<= 1;
        }
        return result;
    }
    string int_to_string(int n) {
        string result = "";
        while(n) {
            if(n%2==1) {
                result="1" + result;
            }
            else {
                result="0" + result;
            }
            n>>=1;
        }
        
        if(result.length()==0) {
            result="0";
        }
        return result;
    }
    string addBinary(string a, string b) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        //small
        //int ai = string_to_int(a);
        //int bi = string_to_int(b);
        //int result = ai + bi;
        //return int_to_string(result);
        
        //large
        string result;
        int carray_bit = 0;
        for(int i=a.length()-1,j=b.length()-1;i>=0 && j>=0; i--,j--) {
            if(a[i]=='0' && b[j]=='0') {
                if(carray_bit==1) {
                    result = "1" + result;
                }
                else {
                    result = "0" + result;
                }
                carray_bit=0;
            }
            else if( (a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0') ){
                if(carray_bit==1) {
                    //carray_bit still 1
                    result = "0" + result;
                }
                else {
                    //carray_bit still 0
                    result = "1" + result;
                }
            }
            else if(a[i]=='1' && b[j]=='1') {
                if(carray_bit==1) {
                    result = "1" + result;
                }
                else {
                    result = "0" + result;
                }
                carray_bit = 1;
            }
        }
        if(result.length()==0) {
            result="0";
        } 
        
        return result;

    }
};


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics