both strings should have all digits
| 55 | |
| 56 | // both strings should have all digits |
| 57 | String |
| 58 | add(StringView const lhs, StringView const rhs) |
| 59 | { |
| 60 | String result("0"); |
| 61 | |
| 62 | StringView other; |
| 63 | if (lhs.length() < rhs.length()) { |
| 64 | other = lhs; |
| 65 | result.append(rhs); |
| 66 | } else { |
| 67 | other = rhs; |
| 68 | result.append(lhs); |
| 69 | } |
| 70 | |
| 71 | bool carry = false; |
| 72 | |
| 73 | auto itr = result.rbegin(); |
| 74 | auto ito = other.crbegin(); |
| 75 | |
| 76 | while (ito != other.crend()) { |
| 77 | int8_t val = tonum(*itr) + tonum(*ito); |
| 78 | if (carry) { |
| 79 | ++val; |
| 80 | } |
| 81 | if (val < 10) { |
| 82 | carry = false; |
| 83 | } else { |
| 84 | val -= 10; |
| 85 | carry = true; |
| 86 | } |
| 87 | |
| 88 | *itr = tochar(val); |
| 89 | |
| 90 | ++itr; |
| 91 | ++ito; |
| 92 | } |
| 93 | |
| 94 | while (result.rend() != itr && carry) { |
| 95 | int8_t val = tonum(*itr) + 1; |
| 96 | if (val < 10) { |
| 97 | carry = false; |
| 98 | } else { |
| 99 | val -= 10; |
| 100 | carry = true; |
| 101 | } |
| 102 | |
| 103 | *itr = tochar(val); |
| 104 | ++itr; |
| 105 | } |
| 106 | |
| 107 | return result; |
| 108 | } |
| 109 | |
| 110 | String |
| 111 | sub(StringView const lhs, StringView const rhs) |