Skip to content

#061 String as an Integer

Adam Kubiś edited this page Oct 28, 2026 · 1 revision

061 String as an Integer

Create a function that takes a string and returns it as an integer.

Current source and tests | Catalog | Testing and tooling

Run this solution

From the cloned repository root, after installing dependencies:

node "Edabit/061 String as an Integer.js"

Assertions are kept alongside the implementation and throw on failure. A successful run exits with code 0. Run every exercise with npm test or both lint and tests with npm run check.

Current implementation and tests

This is the complete executable file, including its imports and inline test cases. Run it from the repository, not as an isolated file copied out of the wiki. Line endings and trailing whitespace are normalized; executable tokens are unchanged.

//Create a function that takes a string and returns it as an integer.
function stringInt(str) {
    return Number.parseInt(str);
}
import * as Test from '../testHelper.js';
Test.assertEquals(stringInt("6"), 6)
Test.assertEquals(stringInt("2"), 2)
Test.assertEquals(stringInt("10"), 10)
Test.assertEquals(stringInt("666"), 666)

Historical reference notes

Cross-language explanation preserved from the study materials

Reference file: #055 String as an Integer.txt. These older notes use a separate numbering scheme and may describe C# code, external diagrams or benchmark timings. They are reference material, not measured JavaScript performance. The current implementation and assertions above are authoritative.

# [Return a String as an Integer](https://edabit.com/challenge/fERoxYvMb5QQkzBML)
Published by [Nomore](https://edabit.com/user/p6ESyNjSyY6QbwMDW)

language_fundamentals numbers strings

Create a function that takes a string and returns it as an integer.

`StringInt("6") ➞ 6`

`StringInt("1000") ➞ 1000`

`StringInt("12") ➞ 12`

All numbers will be whole.

All numbers will be positive.

### Time Complexity:
The time complexity is _O(n)_, where 𝑛 is the length of the input string. This complexity results from iterating over each character in the string exactly once to parse the number (both `int.Parse` and `Convert.ToInt32` and manual approaches).

### Space Complexity:
The space complexity is _O(1)_ because the function only uses a fixed amount of extra space (for `result`, `sign`, and `index` variables), regardless of the input size.
![flowchart](https://diagrams.helpful.dev/d-r2/d-r2:KPj4EPFz)

 Typically use of `int.Parse(txt)` or `Convert.ToInt32(txt)` internally to perform the conversion. Manually parsing the string to convert it to an integer process is essentially broken down into two parts:

1. **Checking and Handling Signs**: The function identifies whether the string represents a positive or negative number.
2. **Parsing Each Character**: It iterates over each character in the string (ignoring the sign if present), and for each valid digit character, it updates the `result` by multiplying the current result by 10 and adding the integer value of the current character.

More refined approach:
![flowchart](https://diagrams.helpful.dev/d-r2/d-r2:WpsexNCk)

//Create a function that takes a string and returns it as an integer.
using BenchmarkDotNet.Attributes;
using System;
namespace Challenges
{
    public class Program55
    {
        public static int StringInt(string txt)
        {
            int result = 0;
            for (int i = 0; i < txt.Length; i++)
            {
                // Convert the character to its integer value
                int digit = txt[i] - '0';
                result = result * 10 + digit;
            }
            return result;
        }
    }
    public class BenchmarkProgram55
    {
        [Benchmark]
        [Arguments("6")]
        [Arguments("2")]
        [Arguments("10")]
        [Arguments("666")]
        public int StringInt(string txt) => Program55.StringInt(txt);
    }
}

using System;
using Challenges.Edabit;
using NUnit.Framework;
namespace Tests
{
    [TestFixture]
    public class Tests55
    {
        [Test]
        [TestCase("6", 6)]
        [TestCase("2", 2)]
        [TestCase("10", 10)]
        [TestCase("666", 666)]
        public void FixedTest(string num, int expectedResult)
        {
            int result = Program55.StringInt(num);
            Assert.That(result, Is.EqualTo(expectedResult));
        }
    }
}

Clone this wiki locally