Workspace String To Integer
0d
Back to questionsDSA Visualizers: 388 Coding Questions

String to Integer visualizer

Learn String to Integer with a step-by-step Strings visualizer, JavaScript source code and a worked example. Practice fundamentals and parsing.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 3Execution step
Reference example · JavaScript
Inspect reference input
"  -42abc"

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
a=a.trimStart();
let sign=a[0]==="-"?-1:1,i=["-","+"].includes(a[0])?1:0,v=0;
while(i<a.length&&/[0-9]/.test(a[i])){
v=v*10+ +a[i];
s("Accumulate digit",{
Array:[...a],Magnitude:[v],Sign:[sign]
},[i]);
i++
}
return Math.max(-2147483648,Math.min(2147483647,v*sign))
};

Execution canvas

Active Changed
STEP 1

Accumulate digit

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Array6 items
Magnitude1 items
Sign1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Strings · Fundamentals and parsing

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

"  -42abc"

Execution steps

  1. Accumulate digit

Computed output

-42
JavaScript reference implementation
const solve = (a,s)=>{
  a=a.trimStart();
  let sign=a[0]==="-"?-1:1,i=["-","+"].includes(a[0])?1:0,v=0;
  while(i<a.length&&/[0-9]/.test(a[i])){
    v=v*10+ +a[i];
    s("Accumulate digit",{
      Array:[...a],Magnitude:[v],Sign:[sign]
    },[i]);
    i++
  }
  return Math.max(-2147483648,Math.min(2147483647,v*sign))
};

Continue learning

Practice related DSA questions in the same topic.