Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can someone with a bit of time, he could explain to me how intensify very large numbers? I'm not talking here about a ready solution, and the only explanation of how to implement the arithmetic. Ideally, it was based on the class std::string.
#edit
I read something about shifts bit, but examples were only in the form of a listing, and I want an explanation of how it works.
You can represent a large number as a sequence of digits in some base, and separately the sign of the number. To do arithmetic, you simply implement the algorithms you learnt at primary school to do addition, long multiplication, etc. There's more efficient algorithms (for example Karatsuba) for doing some operations, but an initial implementation could use the simpler forms.
If you really have to use std::string, you can use the first char to store the sign ('+' or '-'), and then the digits in base 10 in ascii. It's not efficient, but it's perhaps an easy way to get started, and it certainly makes printing the numbers out easy.
Here is something I quickly wrote when I needed (do not remember when). It is:
Buggy;
Not complete;
Arbitrarily use 3 digits per array element while it could use more;
Can clearly be improved (any kind comments are welcome^^).
However, I hope this will be somehow useful.
typedef long long int lli;
class BigInt
{
public: // Methods
BigInt(lli s) : m_nbElements(100)
{
m_number.resize(m_nbElements);
for (lli i=0; i < m_nbElements; ++i)
{
m_number[i] = s%1000;
s /= 1000;
}
}
BigInt(const std::string &str) : m_nbElements(100)
{
m_number.resize(m_nbElements);
size_t sizeStr = str.size();
int i = str.size() - 1;
int thousands = 0;
for (; i >= 2; i -= 3, ++thousands)
{
std::string subStr = str.substr(i-2, 3);
unsigned int value;
std::istringstream(subStr) >> value;
m_number[thousands] = value;
}
// Handle the "first" 1 or 2 digits
if (i >= 0)
{
std::string subStr = str.substr(0, i+1);
unsigned int value;
std::istringstream(subStr) >> value;
m_number[thousands] = value;
}
}
BigInt operator*(lli s)
{
lli temp, remainder = 0;
for (lli i=0; i < m_nbElements; ++i)
{
temp = m_number[i] * s + remainder;
m_number[i] = temp % 1000;
remainder = temp / 1000;
}
return (*this);
}
BigInt operator/(lli s)
{
lli temp, remainder = 0;
for (int i=m_nbElements-1; i >= 0; --i)
{
temp = (m_number[i] + remainder) / s;
remainder = (m_number[i] % s)*1000;
m_number[i] = temp;
}
return (*this);
}
BigInt operator-(BigInt s)
{
lli temp;
for (unsigned int i=0; i < m_nbElements; ++i)
{
temp = m_number[i] - s.m_number[i];
if (temp < 0)
{
--m_number[i+1];
temp += 1000;
}
m_number[i] = temp;
}
return (*this);
}
BigInt operator+(BigInt s)
{
lli temp, remainder = 0;
for (lli i=0; i < m_nbElements; ++i)
{
temp = m_number[i] + s.m_number[i] + remainder;
m_number[i] = temp % 1000;
remainder = temp / 1000;
}
return (*this);
}
std::string ToString()
{
std::string result = "";
bool significantDigitsFound = false;
for (int i=m_nbElements-1; i >= 0 ; --i)
{
if (!significantDigitsFound)
{
if (m_number[i] > 0)
{
std::ostringstream ss;
ss << m_number[i];
result = ss.str();
significantDigitsFound = true;
}
}
else
{
std::ostringstream ss;
ss << std::setw(3) << std::setfill( '0' ) << m_number[i];
result += ss.str();
}
}
if (result == "")
{
result = "0";
}
return result;
}
private: // Attributes
int m_nbElements;
std::vector<lli> m_number;
};
Related
There is this problem on Leetcode , Link of the problem is : https://leetcode.com/problems/largest-time-for-given-digits/
I have written the code for this problem , and according to me my code is correct but still my code is not passing all the test cases and I am stuck debugging where is the issue in my Code .
Can Anybody please help me with this ?
class Solution {
public:
bool isValid(string s){
if(s[0] > '2') return false;
if(s[0] == '2'){
if(s[1] >= '4'){
return false ;
}
}
if(s[2] >=6) return false ;
return true ;
}
vector<vector<int>> permute(vector<int> &nums)
{
vector<vector<int>> result;
//Base Case For The Problem:
if (nums.size() <= 1)
return {nums};
for (int i = 0; i < nums.size(); i++)
{
vector<int> v(nums.begin(), nums.end());
v.erase(v.begin() + i);
auto res = permute(v);
for (int j = 0; j < res.size(); j++)
{
vector<int> _v = res[j];
_v.insert(_v.begin(), nums[i]);
result.push_back(_v);
}
}
return result;
}
string largestTimeFromDigits(vector<int>& A) {
vector<vector<int>> res ;
vector<string> valid ; //For Only Storing the Valid Time Permutations
res = permute(A);
//Now , Iterating Over All the Permutations:
for(int i=0 ; i<res.size() ; i++){
string curr = "";
for(int j=0 ; j<res[i].size() ; ++j){
curr += res[i][j];
}
if(isValid(curr)) valid.push_back(curr);
}
sort(valid.begin() , valid.end());
string ans = ""; //The Final Answer that we have to return at the end.
if(valid.size() > 0){
//Now , perform the Required Operations:
string temp = valid[valid.size() - 1];
ans = temp.substr(0,2) + ":" + temp.substr(2);
}
return ans;
}
};
Two problems in your code, both related to mixing int with char. The first is here:
if(s[2] >=6 ) {
return false ;
}
Because of this condition your isValid returns false always. No character in the range '0'...'9' is smaller than the integer 6. Compare the char to a char:
if(s[2] >='6' ) {
return false ;
}
Next, here
curr += res[i][j];
res[i][j] is an integer, but you want to add a character to the string:
curr += static_cast<char>(res[i][j]) + '0';
After fixing those two I get expected output at least for input {2,2,2,2}, see here: https://godbolt.org/z/35r3f9.
I have to mention that you would have found those problems yourself if you had used a debugger. Getting better in coding is not that much about making less mistakes, but about getting better at finding and fixing them. The debugger is an essential tool to do that.
C++
You can use std::prev_permutation and sort first:
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
#include <vector>
#include <algorithm>
static const struct Solution {
static const std::string largestTimeFromDigits(std::vector<int>& A) {
std::sort(std::begin(A), std::end(A), std::greater<int>());
do if (
(A[0] < 2 || A[0] == 2 && A[1] < 4) &&
A[2] < 6
) {
return std::to_string(A[0]) + std::to_string(A[1]) + ":" + std::to_string(A[2]) + std::to_string(A[3]);
}
while (std::prev_permutation(std::begin(A), std::end(A)));
return "";
}
};
Here is LeetCode's official solution in C++:
class Solution {
public:
string largestTimeFromDigits(vector<int>& A) {
int max_time = -1;
// prepare for the generation of permutations next.
std::sort(A.begin(), A.end());
do {
int hour = A[0] * 10 + A[1];
int minute = A[2] * 10 + A[3];
if (hour < 24 && minute < 60) {
int new_time = hour * 60 + minute;
max_time = new_time > max_time ? new_time : max_time;
}
} while(next_permutation(A.begin(), A.end()));
if (max_time == -1) {
return "";
} else {
std::ostringstream strstream;
strstream << std::setw(2) << std::setfill('0') << max_time / 60
<< ":" << std::setw(2) << std::setfill('0') << max_time % 60;
return strstream.str();
}
}
};
Alternative solution with regular expression:
This'd be difficult in C++ though:
class Solution:
def largestTimeFromDigits(self, A: List[int]) -> str:
for i in range(2359, -1, -1):
if i < 1000:
i = format(i, '04')
if int(re.findall(r'\d{2}$', str(i))[0]) > 59:
continue
l = list(map(int, str(i)))
for j in A:
if j in l:
l.remove(j)
if len(l) == 0:
hm = re.findall(r'.{2}', str(i))
return f'{hm[0]}:{hm[1]}'
return ""
Alternative solution using three loops in Java:
public final class Solution {
public static final String largestTimeFromDigits(
final int[] A
) {
String res = "";
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
for (int k = 0; k < 4; ++k) {
if (i == j || i == k || j == k) {
continue;
}
String hour = "" + A[i] + A[j];
String minute = "" + A[k] + A[6 - i - j - k];
String time = hour + ":" + minute;
if (
hour.compareTo("24") < 0 &&
minute.compareTo("60") < 0 &&
res.compareTo(time) < 0
) {
res = time;
}
}
}
}
return res;
}
}
References
For additional details, please see the Discussion Board where you can find plenty of well-explained accepted solutions with a variety of languages including low-complexity algorithms and asymptotic runtime/memory analysis1, 2.
it is my first question in SO, but I cannot find a good solution for this, not online nor from my brain.
I have a big string of number (over 100 digits) and I need to remove some of its digits to create a number divisible by 8. It is really simple...
However, lets say the only way to create this number is with a number that ends with '2'. In this case I would need to look for proper 10's and 100's digits and it is at this point I cannot find an elegant solution.
I have this:
bool ExistDigit(string & currentNumber, int look1) {
int currentDigit;
int length = currentNumber.length();
for (int i = length - 1; i >= 0; i--) {
currentDigit = -48;//0 in ASC II
currentDigit += currentNumber.back();//sum ASCII's value of char to current Digit
if (currentDigit == look1) {
return true;
}
else
currentNumber.pop_back;
}
return false;
}
It modify the string but since I check for 8's and 0's first, by the time I get to check 2's, the string is empty already. I solved this by creating several copies of the string, but I would like to know if there is a better way and what is it.
I know that if I use ExistDigit(string CurrentNumber, int look1), the string does not get modified, but in this case, it would not help with the 2, because after finding the two I need to look for 1's, 5's and 9's after the 2 in the original string.
What is the correct approach to these kind of problems? I mean, should I stick with changing the string or should I return a value for the position of the 2 (for example) and work from there? If it is good to change the string, how should I do it in order to be able to reuse the original string?
I am new to C++, and coding in general (just started actually) so, sorry if it is a really silly question. Thanks in advance.
EDIT: My call look like this:
int main() {
string originalNumber;//hold number. Must be string because number can be too long for ints
cin >> originalNumber;
string answer = "YES";
string strNumber;
//look for 0's and 8's. they are solutions by their own
strNumber = originalNumber;
if (ExistDigit(strNumber, 0)) {
answer += "\n0";
}
else {
strNumber = originalNumber;
if (ExistDigit(strNumber, 8)) {
answer += "\n8";
}
else {
strNumber = originalNumber;
//look for 'even'32, 'even'72, 'odd'12, 'odd'52, 'odd'92
//these are the possibilities for multiples of 8 ended with 2
if (ExistDigit(strNumber, 2)) {
if (ExistDigit(strNumber, 1)) {
}
}
else {
EDIT 2: In case you have the same problem, check the function find_last_of, it is really convenient and solves the problem.
The following code retains your design and should give at least a solution if one exists. The nested if and for can be simplified within a more elegant solution by using a recursive function. With such a recursive function, you could also enumerate all the solutions.
Instead of having multiple copies of the string, you could use an iterator that defines the start of the search. In the code the start variable is this iterator.
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
bool ExistDigit(const string & currentNumber, int& start, int look1) {
int currentDigit;
int length = currentNumber.length();
for (int i = length - 1 - start; i >= 0; i--) {
currentDigit = currentNumber[i] - '0';
if (currentDigit == look1) {
start = length - i;
return true;
}
}
return false;
}
int main() {
string originalNumber;//hold number. Must be string because number can be too long for ints
cin >> originalNumber;
stringstream answer;
answer << "YES";
//look for 0's and 8's. they are solutions by their own
int start = 0;
if (ExistDigit(originalNumber, start, 0)) {
answer << "\n0";
}
else {
start = 0;
if (ExistDigit(originalNumber, start, 8)) {
answer << "\n8";
}
else {
start = 0;
//look for 'even'32, 'even'72, 'odd'12, 'odd'52, 'odd'92
//these are the possibilities for multiples of 8 ended with 2
if (ExistDigit(originalNumber, start, 2)) {
for (int look2 = 1; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "2";
};
}
};
for (int look2 = 3; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "2";
};
}
//look for 'odd'36, 'odd'76, 'even'12, 'even'52, 'even'92
//these are the possibilities for multiples of 8 ended with 2
else if (ExistDigit(originalNumber, start, 6)) {
for (int look2 = 3; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "6";
};
}
};
for (int look2 = 1; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "6";
};
}
//look for 'even'24, 'even'64, 'odd'44, 'odd'84, 'odd'04
//these are the possibilities for multiples of 8 ended with 2
else if (ExistDigit(originalNumber, start, 6)) {
for (int look2 = 0; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) { // 'odd'
for (int look3 = 1; look3 < 10; look3 += 2) {
int startAttempt2 = startAttempt1;
if (ExistDigit(originalNumber, startAttempt2, look3))
answer << "\n" << look3 << look2 << "4";
};
}
};
for (int look2 = 2; look2 < 10; look2 += 4) {
int startAttempt1 = start;
if (ExistDigit(originalNumber, startAttempt1, look2)) // 'even'
answer << "\n" << look2 << "4";
};
}
}
}
cout << answer.str() << std::endl;
return 0;
}
Here is a solution when you are looking for a subword composed of successive characters in the decimal textual form.
#include <string>
#include <iostream>
bool ExistDigit(const std::string& number, int look) { // look1 = 2**look
// look for a subword of size look that is divisible by 2**look = 1UL << look
for (int i = (int) number.size()-1; i >= 0; --i) {
bool hasFound = false;
unsigned long val = 0;
int shift = look-1;
if (i-shift <= 0)
shift = i;
for (; shift >= 0; --shift) {
val *= 10;
val += (number[i-shift] - '0');
};
if (val % (1UL << look) == 0)
return true;
};
return false;
}
int main(int argc, char** argv) {
std::string val;
std::cin >> val;
if (ExistsDigit(val, 3) /* since 8 = 2**3 = (1 << 3) */)
std::cout << "have found a decimal subword divisible by 8" << std::endl;
else
std::cout << "have not found any decimal subword divisible by 8" << std::endl;
return 0;
}
If you are likely to find a subword of consecutive bits in the binary form of the number, you need to convert your number in a big integer and then to do similar search.
Here is a (minimal-tested) solution without any call to an external library like gmp to convert the text in a big integer. This solution makes use of bitwise operations (<<, &).
#include <iostream>
#include <string>
#include <vector>
int
ExistDigit(const std::string & currentNumber, int look) { // look1 = 2^look
std::vector<unsigned> bigNumber;
int length = currentNumber.size();
for (int i = 0; i < length; ++i) {
unsigned carry = currentNumber[i] - '0';
// bigNumber = bigNumber * 10 + carry;
for (int index = 0; index < bigNumber.size(); ++index) {
unsigned lowPart = bigNumber[index] & ~(~0U << (sizeof(unsigned)*4));
unsigned highPart = bigNumber[index] >> (sizeof(unsigned)*4);
lowPart *= 10;
lowPart += carry;
carry = lowPart >> (sizeof(unsigned)*4);
lowPart &= ~(~0U << (sizeof(unsigned)*4));
highPart *= 10;
highPart += carry;
carry = highPart >> (sizeof(unsigned)*4);
highPart &= ~(~0U << (sizeof(unsigned)*4));
bigNumber[index] = lowPart | (highPart << (sizeof(unsigned)*4));
}
if (carry)
bigNumber.push_back(carry);
};
// here bigNumber should be a biginteger = currentNumber
for (int i = 0; i < bigNumber.size()*8*sizeof(unsigned); ++i) {
// looks for look consective bits set to '0'
bool hasFound = true;
for (int shift = 0; hasFound && shift < look; ++shift)
if (bigNumber[(i+shift) / (8*sizeof(unsigned))]
& (1U << ((i+shift) % (8*sizeof(unsigned)))) != 0)
hasFound = false;
if (hasFound) { // ok, bigNumber has look consecutive bits set to 0
// test if we are at the end of the bigNumber
int index = (i+look) / (8*sizeof(unsigned));
for (int j = ((i+look+8*sizeof(unsigned)-1) % (8*sizeof(unsigned)))+1;
j < (8*sizeof(unsigned)); j++)
if ((bigNumber[index] & (1U << j)) != 0)
return i; // the result is (currentNumber / (2^i));
while (++index < bigNumber.size())
if (bigNumber[index] != 0)
return i; // the result is (currentNumber / (2^i));
return -1;
};
};
return -1;
}
int main(int argc, char** argv) {
std::string val;
std::cin >> val;
std::cout << val << " is divided by 8 after " << ExistDigit(val, 3) << " bits." << std::endl;
return 0;
}
I am designing a cipher and need to convert between bases repeatedly in a loop. I have optimized the everything else, but I'm not too familiar with C++ code, and and am trying to figure out how to make the conversion faster.
Here's the current code I'm using:
string digits = "0123456789abcdef";
string tohex(string number) { // Decimal to Hexadecimal function
long length = number.length();
string result = "";
vector<long> nibbles;
for ( long i = 0; i < length; i++ ) {
nibbles.push_back(digits.find(number[i]));
}
long newlen = 0;
do {
long value = 0;
newlen = 0;
for ( long i = 0; i < length; i++ ) {
value = (value * 10) + nibbles[i];
if (value >= 16) {
nibbles[newlen++] = value / 16;
value %= 16;
} else if (newlen > 0) {
nibbles[newlen++] = 0;
};
};
length = newlen;
result = digits[value] + result;
} while (newlen != 0);
return result;
}
In my case (cipher) the number will always fit within an int, so it works to do:
string tohex(string number) {
int num = std::stoi(number);
std::stringstream hexnumber;
hexnumber << std::hex << num;
return hexnumber.str();
}
This is better because it is simpler and uses the built-in std::hex method.
I've almost solved this exercise:
Binary to Decimal and Back Converter - "Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent."
So, the binary to decimal converter works perfectly, but the other one doesn't. convertToBinary() function returns crap and I don't know why. Here is the code:
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
char* convertToBinary(int dec);
int convertToDec(const char* bin);
int main()
{
std::cout << convertToBinary(100) << std::endl; // wtf!
return 0;
}
char* convertToBinary(int dec)
{
char binary[15] = "";
int result;
for(int i = 0; dec >= 1; dec /= 2, ++i)
{
result = !((dec % 2) == 0);
binary[i] = result + 48;
}
for(int i = strlen(binary); strlen(binary) % 4 != 0; ++i) // add some zeros to make it look cool
binary[i] = '0';
for(int i = 0, j = strlen(binary)-1; i < j; ++i, --j) // reverse the array
{
char temp = binary[i];
binary[i] = binary[j];
binary[j] = temp;
}
std::cout << binary << std::endl; // looking good!
return binary;
}
int convertToDec(const char* bin)
{
int dec = 0;
int size = strlen(bin);
for(int i = 0; *bin; ++i, ++bin)
{
int ch = *bin - 48;
dec += ch * pow(2, size - i - 1);
}
return dec;
}
Using c language
char *convertToBinary(int value)
{
char *binary;
size_t length;
size_t i;
length = 8 * sizeof(value);
binary = malloc(1 + length);
if (binary == NULL)
return NULL;
for (i = 0 ; i < length ; ++i)
binary[length - i - 1] = (value & (1 << i)) ? '1' : '0';
binary[length] = '\0';
return binary;
}
int binaryToDecimal(const char *binary)
{
int value;
size_t length;
size_t i;
value = 0;
length = strlen(binary);
for (i = 0 ; i < length ; i++)
value |= (binary[i] == '1') ? (1 << (length - i - 1)) : 0;
return value;
}
Using c++ language
std::string convertToBinary(int value)
{
std::string binary;
size_t length;
length = 8 * sizeof(value);
binary.resize(length);
for (size_t i = 0 ; i < length ; ++i)
binary[length - i - 1] = (value & (1 << i)) ? '1' : '0';
return binary;
}
int binaryToDecimal(const std::string &binary)
{
int value;
size_t length;
value = 0;
length = binary.length();
for (size_t i = 0 ; i < length ; i++)
value |= (binary[i] == '1') ? (1 << (length - i - 1)) : 0;
return value;
}
to convert from binary to decimal, you can use strtol of course.
Your mistake is returning a local variable, a local variable is automatically deallocated when the function returns, and hence the garbage you got.
When you do something like this:
char *toString(...)
{
char res[MAX_RES];
// fill res
return res;
}
you create the array res as a local array on the stack. This array goes out of scope when you return from the function; a pointer to this array is no longer valid and most likely will point to garbage.
If you want to use C-style char buffers, there are two ways to get around this:
Allocate the result on the heap.
char *toString(...)
{
char *res = malloc(MAX_RES);
// fill res
return res;
}
Data allocated on the heap with malloc will be valid until explicitly released with free. The advantage of this approach is that you can make the string as long as you wish. Thedrawback is that the allocation might fail. It is also worth noting that the caller now owns the string and is responsible for freeing it:
char *x = toString(...);
// do stuff with x
free(x);
**Pass the buffer and maximum length **
int toString(char *res, size_t max, ...)
{
// fill res
}
That is the approach many library functions use, notably snprintf. The caller has to provide their own buffer and information on the maximum allowable length in order to avoid buffer overflows. This approach must keep track of the buffer size and truncate the result if necessary, possibly maintaining the string null-terminated. Such functions could be void, but it is customary to return the actual string length or -1 as error indicator.
It is called like this:
char x[200];
toString(x, sizeof(x), ...);
// do stuff with x
i was looking around the forums and i still couldnt find my answer to my problem.
I got two strings, that are just really an array of numbers. for example(i just choose random numbers
string input1="12345678909876543212";
string input2="12345";
I want to add these two string together but act them like there integers.
My goal is creating a class where i can add bigger numbers than (long long int) so it can exceed the largest long long int variable.
So i revese the string with no problem, so now there
input1="21234567890987654321"
input2="54321"
then i tried adding, let's say input1[0]+input2[0] (2+5) to a new string lets call it newString[0] where that would equal (7); but i cant find a good way to temporally convert the current number in the string so i can add it to the new string? can anyone help. I get sick and tired of atoi,stof,stod. they don't seem to work at all for me.
Any way i can make this function work.
I don't care about making the class yet, i just care about finding a way to add those two strings mathematically but still maintaining the newString's string format. Thank you for whoever can figure this out for me
Okay, so, assuming your only problem is with the logic, not the class design thing, I came up with this logic
fill up the inputs with 0s, checking the lengths, match the lengths
add like normal addition, keeping track of carry
finally remove leading zeros from result
So using std::transform with a lambda function on reverse iterators :-
char carry = 0;
std::transform(input1.rbegin(),input1.rend(),input2.rbegin(),
result.rbegin(),[&carry]( char x, char y){
char z = (x-'0')+(y-'0') + carry;
if (z > 9)
{
carry = 1;
z -= 10;
}
else
{
carry = 0;
}
return z + '0';
});
//And finally the last carry
result[0] = carry + '0';
//Remove the leading zero
n = result.find_first_not_of("0");
if (n != string::npos)
{
result = result.substr(n);
}
See Here
Edit "Can you comment on what your doing here"
+--------+--------------+------------+-------> Reverse Iterator
| | | |
std::transform( | input1.rbegin(), input1.rend(),input2.rbegin(),
result.rbegin(), [&carry]( char x, char y){
//This starts a lambda function
char z = (x-'0')+(y-'0') + carry; // x,y have ASCII value of each digit
// Substracr ASCII of 0 i.e. 48 to get the "original" number
// Add them up
if (z > 9) //If result greater than 9, you have a carry
{
carry = 1; // store carry for proceeding sums
z -= 10; // Obviously
}
else
{
carry = 0; //Else no carry was generated
}
return z + '0'; // Now you have "correct" number, make it a char, add 48
});
std::transform is present in header <algorithm>, see the ideone posted link.
Here's A Solution for adding two numbers represented as strings .
#include<iostream>
using namespace std;
string add(string a, string b)
{
int al=a.size()-1;
int bl=b.size()-1;
int carry=0;
string result="";
while(al>=0 && bl>=0)
{
int temp = (int)(a[al] - '0') + (int)(b[bl] - '0') + carry ;
carry = 0;
if(temp > 9 )
{
carry=1;
temp=temp-10;
}
result+=char(temp + '0');
al--;
bl--;
}
while(al>=0)
{
int temp = (int)(a[al] - '0') + carry ;
carry = 0;
if(temp>9)
{
carry=1;
temp=temp%10;
}
result+=char(temp + '0');
al--;
}
while(bl>=0)
{
int temp = (int)(b[bl] - '0') + carry ;
carry = 0;
if(temp>9)
{
carry=1;
temp=temp%10;
}
result+=char(temp + '0');
bl--;
}
if(carry)
result+="1";
string addition="";
for(int i=result.size()-1;i>=0;i--)
addition+=result[i]; // reversing the answer
return addition;
}
string trim(string a) // for removing leading 0s
{
string res="";
int i=0;
while(a[i]=='0')
i++;
for(;i<a.size();i++)
res+=a[i];
return res;
}
int main()
{
string a;
string b;
cin>>a>>b;
cout<<trim(add(a,b))<<endl;
}
I am not a very femilier with C++ but cant we do this?
int i = stoi( input1[0]);
int j = stoi( input2[0]);
int x = i+j;
Please note this can be done in C++11 Please refer [1] and 2 as well
You can convert a char to an int by subtracting '0' from it:
char sumdigit = (input1[0]-'0') + (input2[0]-'0') + '0';
atoi() would be a better to go, as far as converting input[0] to an int:
int temp = atoi(input.substr(0,1).c_str());
then use stringstream to convert back to string:
stringstream convert;
convert << temp;
string newString = convert.str();
Here is a solution, but this is so far from sensible that it is not even funny.
GCC 4.7.3: g++ -Wall -Wextra -std=c++0x dumb-big-num.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
// dumb big num
// unsigned integer
class DBN {
public:
DBN() : num("0") {}
explicit DBN(const std::string& s) : num(s) {
for (const auto& c : num) {
if (!std::isdigit(c)) { throw std::invalid_argument("DBN::DBN"); } }
std::reverse(std::begin(num), std::end(num)); }
DBN operator+(const DBN& rhs) const {
DBN tmp(*this);
return tmp += rhs; }
DBN& operator+=(const DBN& rhs) {
std::string r;
const int m = std::min(num.size(), rhs.num.size());
int c = 0;
for (int i = 0; i < m; ++i) {
int s = (num[i] - '0') + (rhs.num[i] - '0') + c;
c = s / 10;
s %= 10;
r += static_cast<char>('0' + s); }
const std::string& ref = num.size() < rhs.num.size() ? rhs.num : num;
for (int i = m; i < ref.size(); ++i) {
int s = (ref[i] - '0') + c;
c = s / 10;
s %= 10;
r += static_cast<char>('0' + s); }
if (0 < c) { r += '1'; }
num = r;
return *this; }
friend std::ostream& operator<<(std::ostream& os, const DBN& rhs);
friend std::istream& operator>>(std::istream& os, DBN& rhs);
private:
std::string num;
};
std::ostream& operator<<(std::ostream& os, const DBN& rhs) {
std::string s(rhs.num);
std::reverse(std::begin(s), std::end(s));
return os << s;
}
std::istream& operator>>(std::istream& is, DBN& rhs) {
std::stringstream ss;
char c;
while (is && std::isspace(is.peek())) { is.ignore(); }
while (is) {
if (!std::isdigit(is.peek())) { break; }
is >> c;
ss << c; }
DBN n(ss.str());
rhs = n;
return is;
}
int main() {
DBN a, b, t;
while (std::cin >> a >> b) {
std::cout << a + b << "\n";
(t += a) += b;
}
std::cout << t << "\n";
}
Here it is a simple C++ code
string Sum(string a, string b)
{
if(a.size() < b.size())
swap(a, b);
int j = a.size()-1;
for(int i=b.size()-1; i>=0; i--, j--)
a[j]+=(b[i]-'0');
for(int i=a.size()-1; i>0; i--)
if(a[i] > '9')
{
int d = a[i]-'0';
a[i-1] = ((a[i-1]-'0') + d/10) + '0';
a[i] = (d%10)+'0';
}
if(a[0] > '9')
{
string k;
k+=a[0];
a[0] = ((a[0]-'0')%10)+'0';
k[0] = ((k[0]-'0')/10)+'0';
a = k+a;
}
return a;
}
cited from C - Adding the numbers in 2 strings together if a different length
answer, I write a more readable codeļ¼
void str_reverse(char *beg, char *end){
if(!beg || !end)return;
char cTmp;
while(beg < end){
cTmp = *beg;
*beg++ = *end;
*end-- = cTmp;
}
}
#define c2d(c) (c - '0')
#define d2c(d) (d + '0')
void str_add(const char* s1, const char* s2, char* s_ret){
int s1_len = strlen(s1);
int s2_len = strlen(s2);
int max_len = s1_len;
int min_len = s2_len;
const char *ps_max = s1;
const char *ps_min = s2;
if(s2_len > s1_len){
ps_min = s1;min_len = s1_len;
ps_max = s2;max_len = s2_len;
}
int carry = 0;
int i, j = 0;
for (i = max_len - 1; i >= 0; --i) {
// this wrong-prone
int idx = (i - max_len + min_len) >=0 ? (i - max_len + min_len) : -1;
int sum = c2d(ps_max[i]) + (idx >=0 ? c2d(ps_min[idx]) : 0) + carry;
carry = sum / 10;
sum = sum % 10;
s_ret[j++] = d2c(sum);
}
if(carry)s_ret[j] = '1';
str_reverse(s_ret, s_ret + strlen(s_ret) - 1);
}
test code as below:
void test_str_str_add(){
char s1[] = "123";
char s2[] = "456";
char s3[10] = {'\0'};
str_add(s1, s2, s3);
std::cout<<s3<<std::endl;
char s4[] = "456789";
char s5[10] = {'\0'};
str_add(s1, s4, s5);
std::cout<<s5<<std::endl;
char s7[] = "99999";
char s8[] = "21";
char s9[10] = {'\0'};
str_add(s7, s8, s9);
std::cout<<s9<<std::endl;
}
output:
579
456912
100020