JavaScript編寫自己的atoi()函式
在C語言中,我們有一個函式,它接受一個字串或字元陣列作為引數,並返回一個整數,該整數可能由給定的字串表示。如果當前字串無效,則它只讀取到第一個有效索引,並返回該值。我們將看到完整的程式碼及其解釋。
示例
輸入1
string S = "-9845"
輸出1
-9845
解釋
我們得到一個表示數字的字串,因此我們得到了相同的輸出。
輸入2
string str = "90 uy78"
輸出2
Invalid Input
解釋
給定的字串不是有效的整數,因為它包含小寫英文字元和空格。因此,我們根據它給出了輸出。
輸入3
string str = "539"
輸出3
539
字串有效
我們已經看到了上面的例子,現在讓我們來看一下實現的步驟。
首先,我們將建立一個函式,該函式將字串作為輸入,並返回整數作為返回值。
在函式中,首先我們將建立一個函式來檢查或儲存給定的數字是否為負數,方法是檢查字串的第一個字元。
如果第一個字元是減號,那麼我們將從索引1開始遍歷字串,否則從索引0開始。
我們將建立一個變數來儲存結果,並將其初始化為零。
在每次迭代中,我們將當前整數乘以10,然後將當前數字加到它上面。
要將字串數字轉換為整數值,我們將使用parseInt()函式,該函式接受字元或字串作為輸入,並輸出整數值。
最後,我們將返回最終答案,然後列印它。
示例
// function to convert the string to an integer function atoi(str){ // Assuming the string is valid var neg = 1 // checking for the negative number if(str[0] == '-'){ neg = -1 } var ans = 0; var i = 0; // if the number is the negative number then start from the next index if(neg == -1){ i = i + 1 } while (i < str.length){ ans = ans * 10 + parseInt(str[i]); i = i + 1; } ans = ans* neg return ans; // returning the answer } // defining the input and calling the function str = "-4578038"; // calling the function var ans = atoi(str); // printing the answer console.log("The value of the current number is: " + ans);
輸出
The value of the current number is: -4578038
時間和空間複雜度
上述程式碼的時間複雜度為O(N),其中N是給定字串中字元的數量。
上述程式碼的空間複雜度為O(1),因為我們沒有使用任何額外的空間。
字串可能無效
我們將對大多數函式使用之前的程式碼,但主要的是我們必須檢查給定的字串是否有效。如果字串無效,則我們必須找到它,為此我們將建立一個函式,該函式將接受單個字元作為引數並返回布林值。
我們將透過此函式檢查字串是否包含任何空格或其他非數字字元。
示例
// function to check if the current character is digit or not function check(cha){ for(var i = '0'; i <= '9'; i++){ if(cha == i){ return true; } } return false; } // function to convert the string to an integer function atoi(str){ // Assuming the string is valid var neg = 1 // checking for the negative number if(str[0] == '-'){ neg = -1 } var ans = 0; var i = 0; // if the number is the negative number then start from the next index if(neg == -1){ i = i + 1 } while (i < str.length){ // checking for the invalid case if(check(str[i]) == false){ console.log("The given string represents the invalid number"); return; } ans = ans * 10 + parseInt(str[i]); i = i + 1; } ans = ans* neg // printing the answer console.log("The value of the current number is: " + ans); } // defining the input and calling the function str = "0987653"; // calling the function atoi(str);
輸出
The value of the current number is: 987653
時間和空間複雜度
上述程式碼的時間複雜度為O(N),其中N是給定字串中字元的數量。
上述程式碼的空間複雜度為O(1),因為我們沒有使用任何額外的空間。
結論
在本教程中,我們實現了一個JavaScript程式,用於將字串形式的數字轉換為整數。我們遍歷了字串並檢查當前字串是否表示有效數字。我們建立了一個函式,該函式將檢測字串的當前字元是否為數字。