Sum strings as numbers codewars python

alejandrofcarrera / sum.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

# Only valid with positive integers
# Optimum for Database identifiers.
# Function for summing of larger numbers
def sum ( str1 , str2 ):
# Set temporal structures
__s1 = str ( str1 )
__s2 = str ( str2 )
# Check length of both str
if len ( __s1 ) > len ( __s2 ):
# Interchange values
__tmp = __s1
__s1 = __s2
__s2 = __tmp
# Structure for result
__r = «»
__c = 0
# Calculate length
__n1 = len ( __s1 )
__n2 = len ( __s2 )
# Traverse from end of both strings
for i in range ( __n1 — 1 , — 1 , — 1 ):
# Compute sum of current digits & carry
__s = (
( ord ( __s1 [ i ]) — ord ( ‘0’ )) +
int (( ord ( __s2 [ i + ( __n2 — __n1 )]) — ord ( ‘0’ ))) +
__c
)
__r += str ( __s % 10 )
__c = __s // 10
# Add remaining digits
for i in range ( __n2 — __n1 — 1 , — 1 , — 1 ):
__s = (( ord ( __s2 [ i ]) — ord ( ‘0’ )) + __c )
__r += str ( __s % 10 )
__c = __s // 10
# Add remaining carry
if __c :
__r += str ( __c )
# reverse resultant string
return __r [:: — 1 ]
# Driver code
if __name__ == «__main__» :
print ( sum ( «1001» , «199» ))
Читайте также:  OfficeServ DM

Источник

Sum strings as numbers codewars python

<4kyu>Sum Strings as Numbers

Given the string representations of two integers, return the string representation of the sum of those integers.
A string representation of an integer will contain no characters besides the ten numerals “0” to “9”.

A string representation of two integers is given, and the sum of these integers is returned.
(Note: These two strings will not include any characters except «0» to «9».)

example

sumStrings('1','2') // => '3' sumStrings('','5') // => '5' sumStrings('001','5') // => '6' sumStrings('50095301248058391139327916261','81055900096023504197206408605') // => '131151201344081895336534324866' 

Insteb

// Question 1: function sumStrings(a,b)   var result = ''; var remainder = 0; if(a.length  b.length)   var c = a; a = b; b = c; > for(let i=1;ia.length;i++)  / / From the right side, two counts, and add the last amount, the first remainder is 0 var sum = (a.length-(i-1)>0 ? parseInt(a.substr(a.length-i,1)) : 0) + (b.length-(i-1)>0 ? parseInt(b.substr(b.length-i,1)) : 0) + remainder; // After you go to break, it is the number to be retained. result = sum%10 + result // calculate the remainder remainder = parseInt(sum/10) // If it is, the first bit of A, that is, the remainder is greater than 0, then add the remainder. if(remainder > 0 && i == a.length) result = remainder + result; > return result.replace(/\b(0+)/gi,""); // Remove 0 in front of the string > 

Best Practices

// Question 2: function sumStrings(a, b)   var res = '', c = 0; a = a.split(''); b = b.split(''); while (a.length || b.length || c)   c += ~~a.pop() + ~~b.pop(); res = c % 10 + res; c = c > 9; > return res.replace(/^0+/, ''); > 

Small friends have other better solution, welcome to exchange in the commentary area ~

Источник

Как сложить строки как числа?

На codewars встретил такое задание:
Given the string representations of two integers, return the string representation of the sum of those integers.
Дело в том, что очень большие числа записываются в экспоненциальной форме, а нужно вывести в обычной в виде строки.
Есть популярное решение:

function sumStrings(a, b) < var res = '', c = 0; a = a.split(''); b = b.split(''); while (a.length || b.length || c) < c += ~~a.pop() + ~~b.pop(); res = c % 10 + res; c = c >9; > return res.replace(/^0+/, ''); >

Если переписать на человеческий язык, то получится примерно так:

Выполнять, пока в 'a' или 'b' ещё остались символы, или пока число 'c' не нулевое < Взять по одной цифре с конца из 'a' и 'b', сложить как числа и прибавить к 'c' Дописать к 'res' цифру, которая является остатком от деления 'c' на 10 // То есть это попросту цифра, на которую заканчивается число 'c' Записать в 'c' boolean - было ли оно на этом шаге больше 9 // Если было, то осталась необработанная цифра и нужно делать ещё итерацию >

Отдельно стоит добавить, что если в конце итерации ‘c’ была ‘true’, то в начале следующей итерации к этому значению будет добавлена сумма двух цифр.
При сложении true интерпретируется как 1.
Соответственно, ‘c’ между итерациями переносит единицу в следующий по старшинству разряд и служит вместо той точки, которую мы при ручном сложении в столбик ставим в таких случаях над цифрой.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string «The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog», the sum of the integers is 3635.

RAAD07/Sum_of_integers_in_string-Python-Codewars

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Your task in this kata is to implement a function that calculates the sum of the integers inside a string.

For example, in the string «The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog»,

the sum of the integers is 3635.

About

Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string «The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog», the sum of the integers is 3635.

Источник

Sum strings as numbers codewars python

1. Description of the topic:

2. I answer:

// Sum Numbers function sum (numbers) < "use strict"; var sum = 0; for (var i = 0; i < numbers.length; i++) < sum += numbers[i]; >return sum; >; 
// Sum Numbers sum = function (numbers) < "use strict"; return numbers.reduce(function(t, n)< return t + n; >, 0); >; 

Explanation: reduce function Learn from Beijiyang999’s article https://blog.csdn.net/Beijiyang999/article/details/80186242

  1. The reduce function is a merged method that takes two arguments.
  2. The first argument is the function called on each item. The function accepts four arguments (previous value: Prev, current value: Cur, index of the current value: Index, array object: Array)
  3. The second optional parameter is the initial value of the merged base. This method returns a final value.
  4. arr.reduce(function(prev,cur,index,arr)<>,initialValue)
  5. The specific implementation process is as follows:
    continuously fetches the first two items of the array, executes the target function on it, calculates the return value, and continues the fetch operation as the first element of the array until the array Each item is accessed once and returns the final result
    such as reduce operation on array [1, 2, 3]
[1,2,3] Take out 1, 2, fill in 3 [3,3] Take out 3, 3 and fill in 6 [6] The final result is 6 

Источник

Оцените статью