String(represents an integer) to value


StringViews 2005

Write a function which converts the given string(which represents an integer) to its value.

Example

Input string : “3486”

Output : 3486

Time complexity : O(n)

Algorithm

For positive integers,

a. Initialize result = 0.

b. Traverse the string.

c. For every character in the string, result = result*10 + string[i].

d. Return final result.

For negitive integers, Keep track of negative sign,

a. If string[0] = -, sign = -1.

b. Multiply sign to final result.

c. Return final result.

Algorithm working

Input string : “3468”

Apply algorithm,

Initialize result = 0

a) For i = 0,
result = result*10 + string[i]
result = 0*10 + 3
result = 3

b) For i = 1,
result = result*10 + string[i]
result = 3*10 + 4
result = 34

c) For i = 2,
result = result*10 + string[i]
result = 34*10 + 6
result = 346

d) For i = 3,
result = result*10 + string[i]
result = 346*10 + 3
result = 3468
End loop here,
Final output: 3468

C++ Program

#include <bits/stdc++.h>

using namespace std;

//Functions to convert into integer(only positive )
int Convert(char *string)
{
    int result = 0;
    for (int i = 0; string[i] != '\0'; ++i)
    {
        result = result*10 + string[i] - '0';
    }
    return result;
}
//Function for both positive and negitive  
int ConvertNeg(char *string)
{
    int result = 0;
    // Initialize sign as positive
    int sign = 1;  
    int i = 0;    
    if(string[0] == '-')
    {
        sign = -1;  
        i++;
    }
    for(i;string[i] != '\0'; ++i)
    {
        result = result*10 + string[i] - '0';
    }
    //result with sign
    return sign*result;
}
 
//Main function
int main()
{
    char string[] = "3468";
    int final_value = ConvertNeg(string);
    cout<<final_value;
    return 0;
}

Try It

 

 

Translate »