Determine the integer value of "number length exceeds 15."

While working on a problem in leet code, I managed to come up with a solution that passed all test cases except for one. The input for that particular test case is an array = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]. To solve the issue, I needed to convert the array into a number, add 1 to the entire number, and then convert it back to an array format with the result. In my solution, one step before the final statement, I used parseInt("6145390195186705543")+1, then converted it to a string, split it, and finally converted it back to a number.

However, during the parseInt() process, the built-in method was unable to convert after the 15th digit. The output showed as [6145390195186705000], with zeros being added after the 15 digits. Does anyone have any suggestions on how to convert a string of numbers longer than 16 characters to a Number?

P.S: I tried using the bigInt() method, which technically should work, but for this particular problem, bigInt() is not functioning properly and the output isn't correct.

var plusOne = function(digits) {
  let y = digits.map(String);
  let z = ''
  for (let i = 0; i < y.length; i++) {
    z += y[i];
  }
  let a = (parseInt(z) + 1).toString().split('')
  return a.map(Number)
};

Answer №1

Iterate in reverse order through the digits, checking each one:

  • If the digit is less than 9, add 1 and stop
  • If the digit is 9, set it to 0 and if it was the first digit, insert a 1 at the beginning of the array

function incrementDigits(digitArray) {
  for (let i = digitArray.length - 1; i >= 0; i--) {
    if (digitArray[i] < 9) {
      digitArray[i] += 1
      break
    } else {
      digitArray[i] = 0
      if (i === 0) {
        digitArray.unshift(1)
      }
    }
  }
  return digitArray
}

console.log(incrementDigits([]))         // []
console.log(incrementDigits([ 0 ]))      // [ 1 ]
console.log(incrementDigits([ 9 ]))      // [ 1, 0 ]
console.log(incrementDigits([ 1, 0 ]))   // [ 1, 1 ]
console.log(incrementDigits([ 1, 9 ]))   // [ 2, 0 ]
console.log(incrementDigits([ 9, 9 ]))   // [ 1, 0, 0 ]

console.log(incrementDigits([ 6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3 ]))
// [ 6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3 ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing JSON encoding in PHP to populate a dropdown menu

How can I update a select dropdown with dynamic data every few seconds using PHP and JavaScript? I have a PHP script that retrieves an array of numbers from 1 to 10 and returns it as a JSON response. However, when I try to update the select dropdown with ...

What are the best methods for utilizing scrollbars to navigate a virtual canvas?

I am interested in developing a unique jQuery plugin that can simulate a virtual HTML5 Canvas, where the canvas is not physically larger than its appearance on the page. However, the content intended for display on the canvas may be much larger and will ne ...

Create a custom BoxGeometry with curved edges using Three.JS

Looking to create a curved BoxGeometry in Three.Js, but unsure of how to achieve it. The end result should resemble the image shown here: enter image description here My current code is as follows, however, it does not produce the desired curved effect. ...

Tips for sending variable from JavaScript to PHP Page through XMLHTTP

Make sure to review the description before flagging it as a duplicate. In my understanding, the method of transmitting data from JavaScript to PHP is through Ajax Call. This is the situation I am facing: With PHP, I bring forth an HTML page that cont ...

AngularJS is patiently waiting for the tag to be loaded into the DOM

I am trying to incorporate a Google chart using an Angular directive on a webpage and I want to add an attribute to the element that is created after it has loaded. What is the most effective way to ensure that the element exists before adding the attribut ...

Encountering an error of "undefined is not iterable, cannot read property Symbol(Symbol.iterator)"

While learning React through coding, I encountered an error (Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)). I am unsure where the problem lies. Any suggestions? When utilizing useEffect to activate setFiltere ...

Initiating the accordion feature requires two clicks and triggers an rotation of the icon

I managed to integrate some code I discovered for a FAQ accordion on my website. I am struggling with getting the title to expand with just 1 click instead of 2. Additionally, I would like the icon to rotate when expanding/collapsing, not just on hover. Be ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

I'm looking to extract the values of input fields from a specific form that I have just clicked on. Each form and their input fields share the same class, but each input field contains

When working with a PHP while loop that generates multiple forms with the same id and classes, it can be challenging to target specific input values. Each form input has its own distinct value, but clicking on the submit button of a particular form shoul ...

I encountered an issue while using WooCommerce where I needed the "color section" product attribute to be hidden or disabled when a customer clicked on "stock" in the product price. Unfortunately, I'm unsure of how

function hideStock(){ var selected = document.getElementById("stk"); var hidden = document.getElementById("pa_color"); if (selected.onchange=="stock") { hidden.style.display = "none"; } } <table class= ...

Saving Selected Radio button values into Jquery Array

In my HTML table, there are multiple rows with radio buttons representing the sexes in the 0th position of <td>. I am trying to store the values of sex (either 1 or 0) in an array. Below is a snippet for a table with 3 rows. HTML Code: <table> ...

Unable to persist information in Firebase's real-time database

I'm having trouble saving data to my firebase database. Although I don't see any errors on the site, the data in firebase remains null and doesn't change no matter what I do. Here is the code snippet. HTML <html> <head> ...

Guide on creating a square within an element using JavaScript

After conducting thorough research, I find myself unsure of the best course of action. My situation involves a Kendo Grid (table) with 3 rows and 3 columns. Initially, the table displays only the first column, populated upon the page's initial load. S ...

PHP retrieve rows with matching first words - must be exact matches

$companies = array( array('id' => '1','name' => 'Fifo Limited'), array('id' => '2','name' => 'FIFO Ltd'), array('id' => '3','name& ...

Display a div when collapsing in Bootstrap for screen widths of 991px or smaller

I am currently working on optimizing the mobile version of my website using Bootstrap. There is a div element that is taking up too much space on the page, and I would like to hide it on page load for screen widths of 991px or less. I want users to have th ...

Triggering a sweet alert on a mouse click

Here is a code snippet I found on . It shows an alert box that doesn't disappear when clicked outside of it. swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, ...

Angular Redirect Function: An Overview

In the Angular project I'm working on, there is a function that should navigate to the home when executed. Within this function, there is a condition where if true, it should redirect somewhere. if (condition) { location.url('/home') ...

Achieving proper variable-string equality in Angular.js

In my Angular.js application, I am utilizing data from a GET Request as shown below. var app = angular.module('Saidas',[]); app.controller('Status', function($scope, $http, $interval) { $interval(function(){ ...

Encountering an EJS error stating SyntaxError: a closing parenthesis is missing after the argument list in the file path C:Userscomputer pointDesktopproject2viewshome.ejs

Struggling to retrieve data from app.js through ejs and encountering an error. Pursuing a degree in Computer Science <%- include('header'); -%> <h1><%= foo%></h1> <p class = "home-content">It is a fact that readers ...

Retrieve data from the database in Laravel within the last seven days

I am attempting to retrieve data from the database and consolidate it into a single array. My current approach involves using foreach loops to iterate through each day of the 1st week, executing a query each time to fetch the necessary data. foreach ($li ...