从值中添加或减去

从值中添加或减去

本文介绍了C ++-从值中添加或减去"0"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看下面的代码,我明白了逻辑,但是我似乎无法理解'0'的用途.

  class解决方案{上市:字符串addBinary(字符串a,字符串b){字符串s =";int c = 0,i = a.size()-1,j = b.size()-1;while(i> = 0 || j> = 0 || c == 1){c + = i> = 0吗?a [i-]-'0':0;c + = j> = 0?b [j-]-'0':0;s = char(c%2 +'0')+ s;c/= 2;}返回s;}}; 
解决方案

C和C ++标准要求字符'0'..'9'必须连续且不断增加.因此,要将这些字符之一转换为代表它的数字,您要减去'0',然后将数字转换成代表它的字符,您要添加'0'./p>

I was looking at the code below and I got the logic but I cannot seem to understand what is the use of '0'.

class Solution
{
public:
    string addBinary(string a, string b)
    {
        string s = "";

        int c = 0, i = a.size() - 1, j = b.size() - 1;
        while(i >= 0 || j >= 0 || c == 1)
        {
            c += i >= 0 ? a[i --] - '0' : 0;
            c += j >= 0 ? b[j --] - '0': 0;
            s = char(c % 2 + '0') + s;
            c /= 2;
        }

        return s;
    }
};
解决方案

The C and C++ standards require that the characters '0'..'9' be contiguous and increasing. So to convert one of those characters to the digit that it represents you subtract '0' and to convert a digit to the character that represents it you add '0'.

这篇关于C ++-从值中添加或减去"0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:55