string convertDigitsToBinary(int n) {        string ans;        if (n == 0) return 0;        while (n > 0) {        int rem = n % 2;         ans.push_back((char)('0' + rem));        n /= 2;        }        reverse(ans.begin(), ans.end());        return ans;}I understand how the algorithm works to % the number by 2 and then use the remainder to create the binary representation, I just don't know how it works.I guess I don't see the connection in using the remainder to determine whether the bits are 0 or 1So in the code above: N = 6 would be 110
Decimal to Binary Explanation
algorithms
Remainder is the overkill way of testing the lowest bit.  If you think about it any value % 2 will produce only either 0 or 1, which happens corresponds to the value of the lowest bit.  A more mathematical or alternate way of thinking of is even or odd, which can also obtained by % with 2.  If the value is even, % by 2 yields zero.  And if the value is even, then that means that the lowest bit is zero, so % by 2 yielding zero means the lowest bit is zero.The lowest bit in binary integers represents 20.  The other positions in increasing order represent 21, and beyond.  The only way to make an odd number in binary is to add in 20 = 1, which is done by setting the lowest bit.  (Note this also applies to negative numbers as long as they are stored in 2's complement form as all modern computers do).Re: the overkill, in most languages you can do a simpler mask with constant 1, such as n & 1, which is a more direct way of checking the value of the lowest bit.  Divide by 2 is the mathematical way of shifting the bits one position to the right; as with masking, most languages have a the more direct way of shifting, e.g. n >>= 1;  These are often preferred because they have fewer issues, such as the quirks of dealing with mod and division of negative integers (computer division, especially with integers, differs subtly from mathematical division, which would result in fractions or reals).  Also, especially on older processors the simpler way was faster, being doable with simple logic instead of a divider which is fairly complex.