이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

Lunar Arithmetic

Lunar(Dismal) Arithmetic 라는 어떤 연산이 있습니다. 이 연산에서 덧셈「+」은 각 자릿수를 비교해서 큰 수를 취합니다.

5 + 3 = 5
13 + 6 = 16

   169
 + 248
 ------
   269

그리고 곱셈「×」은 각 자릿수를 비교해서 작은 수를 취합니다.

5 × 3 = 3
13 × 6 = 13

     169
   × 248
   ------
     168
    144
 + 122
 --------
   12468

Lunar Arithmetic를 수행하는 계산기를 만들어봅시다.

2019/09/05 17:45

AY

곱셈 x의 연산에 대해서 좀더 설명해주실 수 있을까요? 169 × 248이 잘 이해가 안 되어서요^^;;; - Katherine, 2019/10/09 00:51
+1 Katherine님 248의 8과 169의 각 자리수를 비교해서 작은 걸 취한 것이 결과(248의 밑 줄)의 첫 번째 줄이고, 4와 169의 각 자리수를 비교한 것이 두 번째 줄이고, 2랑 비교한게 세 번째 줄인 것 같네요~ 그걸 한 자리씩 비켜가면서 적은 다음 +연산을 시행한게 제일 밑 줄인 것 같습니다! - GG, 2019/10/11 13:43
+1 Katherine님 일반적인 곱셈을 보면 각 자릿수를 곱하고 더하는 과정이 있죠. 예시로 14*23을 한다면 (4*3)+(4*20)+(10*3)+(10*20) = 12+80+30+200 = 322가 되겠죠. 세로셈으로 쓰면 (14*3)+(14*20) = 42+280 = 322가 되죠. 14*23을 Lunar 연산으로 한다면 (4*3)+(4*20)+(10*3)+(10*20) = 3+20+10+100 = 123 이 됩니다. 세로셈으로 쓰면 (14*3)+(14*20) = 13+120 = 123이 됩니다. - AY, 2019/10/11 14:42
@허혜진 님 @AY 님 좋은 댓글 감사합니다 ^^ 한번 풀어보겠습니다 :) - Katherine, 2019/10/12 12:22

18개의 풀이가 있습니다.

Python 3.7

def ladd(a, b):
    c = ''
    a, b = str(a)[::-1], str(b)[::-1]
    for i in range(max(len(a), len(b))):
        c += max(a[i:i+1], b[i:i+1])
    return int(c[::-1])

def lmul(a, b):
    c = []
    a, b = str(a)[::-1], str(b)[::-1]
    for i in range(len(b)):
        d = ''
        for j in range(len(a)):
            d += min(a[j], b[i])
        c.append('0'*i+d)
    e = 0
    for i in c:
        e = ladd(e, i[::-1])
    return e
Input
ladd(169, 248)
lmul(169, 248)
Output
269
12468

2019/09/06 10:35

AY

간결하고 이해하기 쉽게 잘 짜셨네요!! - Chang-Hoon Lee, 2020/08/21 14:06
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    a, _ := LunarAdd(169, 248)
    m, _ := LunarMul(169, 248)
    fmt.Println(a, m)
}

func LunarAdd(l, r uint) (uint64, error) {
    if l < r {
        l, r = r, l
    }
    return strconv.ParseUint(rawLunaAdd(fmt.Sprint(l), fmt.Sprint(r)), 10, 64)
}
func rawLunaAdd(left, right string) string {
    lenL, lenR := len(left), len(right)
    var buf strings.Builder
    buf.Grow(lenL)
    buf.WriteString(left[:lenL-lenR])
    tmp := left[lenL-lenR:]
    for i := 0; i < lenR; i++ {
        if tmp[i] > right[i] {
            buf.WriteByte(tmp[i])
        } else {
            buf.WriteByte(right[i])
        }
    }
    return buf.String()
}
func LunarMul(l, r uint) (uint64, error) {
    if l < r {
        l, r = r, l
    }
    return strconv.ParseUint(rawLunaMul(fmt.Sprint(l), fmt.Sprint(r)), 10, 64)
}
func rawLunaMul(left, right string) string {
    lenL, lenR := len(left), len(right)
    box := make([]string, 0, lenR)
    var buf strings.Builder
    for i, rv := range right {
        buf.Reset()
        buf.Grow(lenL + lenR - i - 1)
        for _, lv := range left {
            if lv < rv {
                buf.WriteRune(lv)
            } else {
                buf.WriteRune(rv)
            }
        }
        for j := 0; j < lenR-i-1; j++ {
            buf.WriteByte('0')
        }
        box = append(box, buf.String())
    }
    switch lenR {
    case 1:
        return box[0]
    default:
        res := rawLunaAdd(box[0], box[1])
        for id := 2; id < lenR; id++ {
            res = rawLunaAdd(res, box[id])
        }
        return res
    }
}

2019/09/06 17:26

Creator

def ladd(a, b):
    a, b, c = list(str(a)), list(str(b)), ''
    while a or b:
        c = max('0' if not a else a.pop(),
                '0' if not b else b.pop()) \
            + c

    return int(''.join(c))


def lmul(a, b):
    a, b = list(str(max(a, b))), list(str(min(a, b)))
    c, base = 0, 1
    for _b in reversed(b):
        _c = int(''.join([min(x, _b) for x in a]))
        c = ladd(c, _c * base)
        base *= 10

    return c

2019/09/09 09:52

Noname

Ruby

Digit hash에 넣은 뒤 누산

class Integer
  def add(another, hash = create_digit_hash)
    pre_cal(self, another).each { |num| num.each { |n,dgt| hash[dgt] << n } }
    lunar_add(hash)
  end

  def mul(another, hash = create_digit_hash)
    num1, num2 = pre_cal(self, another)
    lunar_mul = ->(two_dgt) { hash[two_dgt.sum(&:last)] << two_dgt.map(&:first).min }
    num2.each { |num2_digit| num1.product([num2_digit]).each &lunar_mul }
    lunar_add(hash)
  end

  private

  def create_digit_hash
    hash = Hash.new { |h,k| h[k] = [] }
  end

  def pre_cal(num1, num2)
    [num1, num2].map { |num| num.digits.map.with_index.to_a }
  end

  def lunar_add(hash)
    hash.values.map(&:max).reverse.join.to_i
  end
end

Test

cases = [[5, 3], [13, 6], [0, 10], [9, 123], [169, 248]]
expect(cases.map {|a,b| a.add(b) }).to eq [5, 16, 10, 129, 269]
expect(cases.map {|a,b| a.mul(b) }).to eq [3, 13,  0, 123, 12468]

Output

169.add 248 #=> 269
169.mul 248 #=> 12468

2019/09/09 17:35

rk

C#. 연산자 오버라이딩 방식으로 접근했습니다.

using System;
using System.Collections.Generic;
using System.Text;

namespace CD241
{
    class Program
    {
        static void Main()
        {
            List<int[]> testCases = new List<int[]>()
            {
                new int[]{5, 3},
                new int[]{13, 6},
                new int[]{169, 248},
            };

            foreach (int[] test in testCases)
            {
                var value1 = new Lunar(test[0]);
                var value2 = new Lunar(test[1]);
                Console.WriteLine($"{value1.NumValue} + {value2.NumValue} = {(value1 + value2).NumValue}");
                Console.WriteLine($"{value1.NumValue} * {value2.NumValue} = {(value1 * value2).NumValue}");
            }
        }
    }

    class Lunar
    {
        public int NumValue { get; } // Lunar 인스턴스의 숫자값

        public string StrValue { get; } // Lunar 인스턴스 숫자값의 문자열 표현

        public int Length => StrValue.Length; // Lunar 인스턴스 숫자값의 길이

        public Lunar(int aNumber)
        {
            NumValue = aNumber;
            StrValue = aNumber.ToString();
        }

        // + 연산자 오버라이딩
        public static Lunar operator +(Lunar lunar1, Lunar lunar2)
        {
            // + 연산을 수행할 값의 길이를 맞춤
            (int length, string string1, string string2) =
                PadLeftLongest(lunar1.StrValue, lunar2.StrValue);

            // 각 자리별 최대값을 선택하여 Lunar 인스턴스 반환
            StringBuilder sb = new StringBuilder();
            for (int idx = 0; idx < length; idx++)
            {
                int addValue =
                    (int)Math.Max(char.GetNumericValue(string1[idx]),
                    char.GetNumericValue(string2[idx]));
                sb.Append(addValue);
            }
            return new Lunar(int.Parse(sb.ToString()));
        }

        // * 연산자 오버라이딩
        public static Lunar operator *(Lunar lunar1, Lunar lunar2)
        {
            Lunar result = new Lunar(0);
            // 각 자리별로 최소값을 선택
            for (int idx1 = 0; idx1 < lunar1.Length; idx1++)
            {
                StringBuilder sb = new StringBuilder();
                for (int idx2 = 0; idx2 < lunar2.Length; idx2++)
                {
                    int addValue =
                        (int)Math.Min(char.GetNumericValue(lunar1.StrValue[idx1]),
                        char.GetNumericValue(lunar2.StrValue[idx2]));

                    sb.Append(addValue);
                }
                // 각 자리별 * 연산자 결과에 대한 + 연산자 수행을 위해 자리수 맞춤
                sb.Append(new string('0', lunar1.Length - idx1 - 1));
                result += new Lunar(int.Parse(sb.ToString()));
            }
            return result;
        }

        // 두 문자열 중 긴 문자열을 기준으로 좌측에 '0'을 채워 반환
        public static (int, string, string) PadLeftLongest(string string1, string string2)
        {
            int maxLength = Math.Max(string1.Length, string2.Length);
            return (maxLength, string1.PadLeft(maxLength, '0'), string2.PadLeft(maxLength, '0'));
        }
    }
}

2019/09/17 14:01

mohenjo

def lunar_arithmetic(choice, *num): init_list = [] init_list_2 = [] len_list = [] digit = [] digit_2 = [] if choice == "add": for i in num: j = str(i) init_list.append(j) for k in init_list: len_list.append(len(k)) max_len = max(len_list) for l in range(0, max_len): for k in init_list: if len(k) < max_len: k = "0" * (max_len - len(k)) + k digit.append(k[l]) digit_2.append(max(digit)) digit = [] sol = "" for number in digit_2: sol = sol + str(number) if choice == "multiple": for i in num: j = str(i) init_list.append(j) for k in init_list: len_list.append(len(k)) max_len = max(len_list) for l in range(0, max_len): for k in init_list: if len(k) < max_len: k = "0" * (max_len - len(k)) + k digit.append(k[l]) if "0" in digit: digit.remove("0") digit_2.append(min(digit)) digit = [] sol = "" for number in digit_2: sol = sol + str(number) return sol

2019/09/18 17:35

남이승윤

문제에서 시킨대로 구현한 코드입니다.

덧셈에 대한 항등원 0이라는 존재가 있기 때문에, 일반적으로 우리가 n^2 곱셈을 하는 방식과 동일하게 구현할 수 있었습니다.

입력 예제 
5 3
16 3
169 248
2312314649516519516515919 51995498794561321987951687916
0 0
123 0
123456789123456789 987654321987654321
...
출력 예제
#1 sum : 5 mul : 3
#2 sum : 16 mul : 13
#3 sum : 269 mul : 12468
#4 sum : 51995498794669526989956687919 mul : 23233345466996698996698799999999997966698997968797916
#5 sum : 0 mul : 0
#6 sum : 123 mul : 0
#7 sum : 987656789987656789 mul : 12345678987655678987655678987654321
...
#include<stdio.h>
int al, bl, cl, dl;
char xx[1000009];
int a[1000009];
int b[1000009];
int d[1000009];
int c[2000009];
__inline int max(int p, int q) { return p > q ? p : q; }
__inline int min(int p, int q) { return p < q ? p : q; }
int main()
{
    int tv = 0;
    while (1) {
        scanf("%s", xx);
        for (al = 0; xx[al]; al++);
        for (int i = 0; i < al; i++)a[i] = xx[al - i - 1] - '0';
        scanf("%s", xx);
        for (bl = 0; xx[bl]; bl++);
        for (int i = 0; i < bl; i++)b[i] = xx[bl - i - 1] - '0';
        cl = al + bl;
        dl = max(al, bl);
        for (int i = 0; i < cl; i++)c[i] = 0;
        for (int i = 0; i < dl; i++)d[i] = 0;
        for (int i = al; i < dl; i++)a[i] = 0;
        for (int i = bl; i < dl; i++)b[i] = 0;
        for (int i = 0; i < dl; i++)d[i] = max(a[i], b[i]);
        for(int i=0;i<al;i++)
            for (int j = 0; j < bl; j++) {
                c[i + j] = max(c[i + j], min(a[i], b[j]));
            }
        for (dl; dl > 1; dl--) if (d[dl - 1])break;
        for (cl; cl > 1; cl--)if (c[cl - 1])break;
        printf("#%d ", ++tv);
        printf("sum : ");
        for (int i = dl - 1; i >= 0; i--)printf("%d", d[i]);
        printf(" mul : ");
        for (int i = cl - 1; i >= 0; i--)printf("%d", c[i]);
        printf("\n");
    }
}

2019/09/27 22:02

pichulia

package d241_Lunar_Arithmetic;
import java.util.Scanner;
public class LunarArithmetic {
    int cipher(int input) { //숫자의 자릿수 구하기
        int i, j;
        for(i=0, j=1; input/j>0; j*=10, i++); //0이 될때까지 나누어보고, 그 횟수를 리턴.
        return i;

    }
    int digit_n(int input, int cipher) { //특정 자릿수(cipher번째) 숫자만 구하기(일의 자리로)
        int result, i, j=1;
        for(i=0; i<cipher-1; i++) j*=10;
        result=input/j;
        result%=10;
        return result;
    }
    int digit(int input, int cipher) { //특정 자릿수(cipher번째) 숫자 구하기(그 자릿수 숫자로)
        int result, i, j=1;
        for(i=0; i<cipher-1; i++) j*=10;
        result=input/j;
        result%=10;
        for(i=0; i<cipher-1; i++) result*=10; //digin_n과의 유일한 차이점.
        return result;
    }

    int plus(int X, int Y) { //'+'연산
        LunarArithmetic la=new LunarArithmetic();
        int x_cipher=la.cipher(X), y_cipher=la.cipher(Y), result=0;
        int max_cipher=(x_cipher>y_cipher)?x_cipher:y_cipher;

        for(int i=1; i<=max_cipher; i++) {
            result+= (la.digit(X, i)>la.digit(Y, i))?la.digit(X, i):la.digit(Y, i);
        }
        return result;
    }

    public static void main(String[] args) {
        LunarArithmetic la=new LunarArithmetic();
        Scanner sc=new Scanner(System.in);

        System.out.println("Input a number, an operator and another number:");
        int X=sc.nextInt(); //입력 받기
        String C=sc.next();
        int Y=sc.nextInt();

        switch(C) {
        case "+": //'+'연산 함수 실행
            int result=la.plus(X, Y);
            System.out.println(" "+X+" "+C+" "+Y+" = "+result);
            break;

        case "×": //모두 '×' 연산
        case "x":
        case "X":
        case "*":
            int X_cipher=la.cipher(X), Y_cipher=la.cipher(Y), resultx=0, y_each;
            int[] array=new int[Y_cipher];
            System.out.println("  "+X+"\n× "+Y); //입력값 한번 더 출력
            System.out.println("-------");
            for(int i=0; i<Y_cipher; i++) {
                y_each=la.digit_n(Y, i+1); //각 줄에서 연산할 Y의 숫자 하나
                array[i]=0;
                for(int j=1; j<=X_cipher; j++) { //각 줄 '×'연산
                    array[i]+= (la.digit(X, j)<y_each)? la.digit(X, j):y_each;
                    y_each*=10;
                }
                for(int j=0; j<i; j++) array[i]*=10; //각 줄 마다 뒤에 0을 붙임
                System.out.print("  "); 
                for(int j=0; j<Y_cipher-i-1; j++) System.out.print(" "); //출력의 편의를 위하여
                System.out.println(array[i]); //각 줄 출력
                resultx=la.plus(resultx, array[i]); //각 줄끼리 '+'연산
            }
            System.out.println("-------");
            System.out.println("  "+resultx);
            break;

        default:
            System.out.println("Input '+' or '×'(or *, x, X).");
            break;
        }

    }
}

#예제1
Input a number, an operator and another number:
169 + 248
 169 + 248 = 269

#예제2
Input a number, an operator and another number:
2438 * 1475
  2438
× 1475
-------
     2435
    24370
   243400
  1111000
-------
  1244475

2019/10/13 10:50

Katherine

솔직히 깔끔했다.

#include <iostream>
#include <cmath>
using namespace std;

int main(){
    int n,m,sum=0,i=0;
    char c;
    cin>>n>>c>>m;

    if(c=='+'){
        while((n!=0) && (m!=0)){
            if((n%10)>(m%10))
                sum+=((n%10)*(pow(10,i)));
            else
                sum+=((m%10)*(pow(10,i)));

            n/=10;
            m/=10;
            i++;
        }
    }

    else if(c=='*'){
        while(n!=0 && m!=0){
            if((n%10)<(m%10))
                sum+=((n%10)*(pow(10,i)));
            else
                sum+=((m%10)*(pow(10,i)));

            n/=10;
            m/=10;
            i++;
        }
    }
    cout<<sum;
}

2019/10/19 12:34

저택벚꽃

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Sum(5, 3);
            Sum(13, 6);
            Sum(169, 248);
            Mul(5, 3);
            Mul(13, 6);
            Mul(169, 248);
        }

        static void Sum (int a, int b) // 덧셈 연산
        {
            int longer_digit = Math.Max(a.ToString().Length, b.ToString().Length); // 큰 자릿수 찾기
            string a_digit = a.ToString().PadLeft(longer_digit, '0'); // 두 수의 자릿수 맞추기
            string b_digit = b.ToString().PadLeft(longer_digit, '0');
            for(int i = 0; i < longer_digit; i++)
            {
                Console.Write((a_digit[i] >= b_digit[i]) ? a_digit[i] : b_digit[i]);
            }
            Console.WriteLine();
        }

        static void Mul (int a, int b) // 곱셈 연산
        {
            List<string> result = new List<string> { };
            int max = 0;
            int digit = 1; // 자릿수
            string temp = ""; // 값 임시 저장
            string a_str = a.ToString();
            string b_str = b.ToString();
            for(int i = b_str.Length - 1; i >= 0; i--)
            {
                for(int x = a_str.Length - 1; x >= 0; x--)
                {
                    temp = ((b_str[i] <= a_str[x]) ? b_str[i] : a_str[x]) + temp;
                }
                result.Insert(0, (int.Parse(temp) * digit).ToString());
                digit *= 10;
                temp = "";
            }
            int result_length = result[0].Length;
            for(int i = 0; i < result.Count; i++)
            {
                result[i] = result[i].PadLeft(result_length, '0');
            }
            for (int i = 0; i < result_length; i++)
            {
                for(int x = 0; x < result.Count; x++)
                {
                    max = Math.Max(int.Parse(result[x][i].ToString()), max);
                }
                Console.Write(max);
                max = 0;
            }
            Console.WriteLine();
        }
    }
}

2019/10/22 22:53

bat

import re

def add(a, b) :
    a = a.rjust(len(b), '0')
    result = ''
    for IND in range(0, len(a)) :
        result += max(a[IND], b[IND])
    return result
def mul(c, d) :
    result = []
    for m in range(1, len(d)+1) :
        RIN = ''
        for n in range(0, len(c)) :
            RIN += str(min(int(c[n]), int(d[-m])))
        RIN += '0'*(m-1)
        result.append(RIN)
    for w in range(1, len(result)) :
        result[0] = add(result[0], result[w])
    return result[0]

inp = input("INPUT : ")

numbs = re.compile("\d+")
oper = re.compile("[+x]{1}")
numbs_LIST, oper_LIST = numbs.findall(inp), oper.findall(inp)

if oper_LIST[0] == "+" :
    print(add(sorted(numbs_LIST)[0], sorted(numbs_LIST)[1]))
elif oper_LIST[0] == "x" :
    print(mul(numbs_LIST[0], numbs_LIST[1]))

결과

INPUT : 169x248
12468

INPUT : 169+248
269

2019/11/28 16:24

GG

def LAp(x,y):
    elst=[]
    xl,yl=list(x),list(y)
    if len(xl)>len(yl):
        yl=["0"]*(len(xl)-len(yl))+yl
    elif len(yl)>len(xl):
        xl=["0"]*(len(yl)-len(xl))+xl
    for i in range(len(xl)):
        if int(xl[i])>=int(yl[i]):
            elst.append(xl[i])
        else:
            elst.append(yl[i])
    return "".join(elst)
print(LAp("169","248")) #269

def LAm(x,y):
    elst=[]
    if int(x)<int(y):
        x,y=y,x
    xl,yl=list(x),list(y)
    for i in range(len(yl)):
        e=""
        for k in range(len(xl)):
            e+=str(min(int(xl[k]),int(yl[i])))
        e="0"*(i)+e+"0"*(len(yl)-i-1)
        elst.append(e)
    if len(xl)==1 and len(yl)==1:
        return "".join(min(xl,yl))
    for i in range(len(elst)-1):
        temp=LAp(elst[i],elst[i+1])
        elst[i+1]=temp
    return elst[i+1]

print(LAm("169","248")) #12468

2020/03/08 21:40

박시원

#파이썬
#별것 아닌 문제인줄 알았는데 코드가 좀 길어져 버렸습니다
#좀 더 간단히 할 수 있는 방법도 있을것 같은데 아직 초보라 잘안되네요 ㅠㅠ

def num_list(a):                #숫자형을 리스트 형으로 변환해 주는 함수
    a,b=str(a),[]
    for i in range (len(a)):
        b.append(int(a[i]))
    return(b)

def conv_num(x):                #리스트형을 숫자로 변환해주는 함수
    z=0
    for i in range (len(x)):
        z+=x[i]*10**(len(x)-1-i)
    return(z)

def check_type(x):              # 변수를 체크하여 숫자형일 경우 리스트 형으로 변환해 주는 함수
    if type(x)==int:
        x=num_list(x)
    return (x)


def hap(x,y):                   #합을 구하는 함수
    x=check_type(x)
    y=check_type(y)

    if len(x)>len(y):
        for i in range (len(x)-len(y)):
            y.insert(0,0)
    elif len(y)>len(x):
        for i in range (len(y)-len(x)):
            x.insert(0,0)

    z=[]
    for i in range (len(x)):
        if x[i]>=y[i]:
            z.append(x[i])
        else:
            z.append(y[i])              

    z=conv_num(z)   
    return (z)

def gop(x,y):               #곱을 구하는 함수
    z=[]

    x=check_type(x)
    y=check_type(y)

    i=len(y)-1
    while (i>=0):
        temp=[]
        for j in range (len(x)):
            if x[j]<=y[i]:
                temp.append(x[j])
            else:
                temp.append(y[i])

        for k in range (len(y)-i-1):
            temp.append(0)

        i-=1
        z=hap(temp,z)

    return (z)

print ('5+3=',hap(5,3))
print ('13+6=',hap(13,6))
print ('169+248=',hap(169,248))
print ('1234+789=',hap(1234,789))
print ('7145+913=',hap(7145,913))
print()
print ('5x3=',gop(5,3))
print ('13x6=',gop(13,6))
print ('169x248=',gop(169,248))
print ('1234x789=',gop(1234,789))
print ('7145x913=',gop(7145,913))

2020/05/03 08:24

Buckshot

<결과> 5+3= 5 13+6= 16 169+248= 269 1234+789= 1789 7145+913= 7945 5x3= 3 13x6= 13 169x248= 12468 1234x789= 123444 7145x913= 714533 - Buckshot, 2020/05/03 08:24

푸는 과정이 재미있는 문제네요.

def runa_add(a,b):
    a_s=str(a)
    b_s=str(b)
    if len(b_s) > len(a_s):
        a,b = b,a
        a_s,b_s = b_s, a_s
    fore_a_s = a_s[:len(a_s)-len(b_s)]
    back_a_s = a_s[len(a_s)-len(b_s) :]
    for i in range(0,len(b_s)):
        if back_a_s[i] > b_s[i]:
            fore_a_s = fore_a_s + back_a_s[i]
        else:
            fore_a_s = fore_a_s + b_s[i]
    answer = int(fore_a_s)
    return answer

def runa_mul(a,b):
    a_s=str(a)
    b_s=str(b)
    e = 1
    if len(b_s) > len(a_s):
        a,b = b,a
        a_s,b_s = b_s, a_s
    for i in range(len(a_s)-1,-1,-1):
        c=""
        for j in range(0,len(b_s)):
            if int(a_s[i]) < int(b_s[j]):
                c = c + a_s[i]
            else:
                c = c + b_s[j]
        if i == len(a_s)-1:
            answer = int(c)
        else:
            e = e * 10
            answer = runa_add(answer, int(c)*e)
    return answer

while True:
    try:
        a1 = int(input("input 1st integer : "))
        b1 = int(input("input 2nd integer : "))
        if "-" in str(a1) or "-" in str(b1):
            print("input positive interger!!")
            break
        else:
            c = runa_add(a1,b1)
            d = runa_mul(a1,b1)
            print("{} runa_add {} = {}".format(a1, b1, c))
            print("{} runa_multiply {} = {}".format(a1, b1, d))
            break
    except ValueError:
        print("That was no valid number.  Try again...")

2020/06/05 16:48

Stony Lee

# Luna Add
def add(a, b):
    a = str(a)
    b = str(b)
    c = ''
    num_digit = max(len(a), len(b))
    a = (num_digit - len(a)) * '0' + a
    b = (num_digit - len(b)) * '0' + b
    for i in range(num_digit):
        c += max(a[i], b[i])
    return int(c)

# Lunar Multiply
def multiply(a, b):
    c = ''
    a = str(a)
    b = str(b)
    num_digit = max(len(a), len(b))
    a = (num_digit - len(a)) * '0' + a
    b = (num_digit - len(b)) * '0' + b
    for ix_b in range(num_digit):
        tmp = ''
        for ix_a in range(num_digit):
            # print(min(a[ix_a], b[ix_b]), end='')
            tmp += min(a[ix_a], b[ix_b])
        # print('0' * (num_digit - ix_b - 1))
        tmp += '0' * (num_digit - ix_b -1)
        c = add(tmp, c)
    return c

2020/08/21 14:02

Chang-Hoon Lee

def ladd(a, b):
    c = ''
    a, b = str(a)[::-1], str(b)[::-1]
    for i in range(max(len(a), len(b))):
        c += max(a[i:i+1], b[i:i+1])
    return int(c[::-1])

def lmul(a, b):
    c = []
    a, b = str(a)[::-1], str(b)[::-1]
    for i in range(len(b)):
        d = ''
        for j in range(len(a)):
            d += min(a[j], b[i])
        c.append('0'*i+d)
    e = 0
    for i in c:
        e = ladd(e, i[::-1])
    return e

2020/10/07 12:08

김빈's life

def plus():
    a=[]
    b=[]
    A=input("숫자입력 : ")
    for i in range(len(A)):
        a.append((int(A[i])))
    B = input("숫자입력 : ")
    for i in range(len(B)):
        b.append((int(B[i])))
    if len(a) != len(b):
        if len(a)>len(b):
            for i in range(1,len(b)+1):
                if a[-i]<b[-i]:
                    a[-i]=b[-i]
            for i in a:
                print(i, end='')
        else:
            for i in range(1,len(a)+1):
                if a[-i]>b[-i]:
                    b[-i]=a[-i]
            for i in b:
                print(i, end='')
    else:
        for i in range(1,len(a)+1):
            if a[-i]<b[-i]:
                a[-i]=b[-i]
        for i in a:
            print(i, end='')



def mul():
    a=[]
    b=[]
    c=[]
    total=[]
    A=input("숫자입력 : ")
    for i in range(len(A)):       
        a.append((int(A[i])))
    B = input("숫자입력 : ")
    for i in range(len(B)):
        b.append((int(B[i])))   # 숫자를 받은후 리스트 형식으로 변환

    if len(a) != len(b):   # 수의 단위 다를경우
        if len(a)>len(b):
            for i in range(1,len(b)+1):
                if a[-i]>b[-i]:
                    a[-i]=b[-i]
            for i in a:
                print(i, end='')
        else:
            for i in range(1,len(a)+1):
                if a[-i]<b[-i]:
                    b[-i]=a[-i]
            for i in b:
                print(i, end='')

    else:                       # 수의 단위 같을경우
        for i in range(1,len(a)+1):
            for j in range(1,len(b)+1):
                if b[-i]<a[-j]:
                    a[-j]=b[-i]          # 비교
            c.append(list(a))
        for i in range(len(c)):       # 자리수 맞추기
            for j in range(i):
                c[i].append(0)
        for i in range(len(c)-1):
            for j in range(1,len(c[i])+1):
                if c[i][-j]>c[i+1][-j]:
                    c[i+1][-j]= c[i][-j] 
        for j in c[-1]:
            print(j, end='')



def Lunar():
    a = input("곱셈선택 : 0 덧셈선택 : 1 : ")
    if a=='0':
        mul()
    elif a=='1':
        plus()
    else:
        print("다시 입력하세요! ")
Lunar()

2021/04/15 21:41

fox.j

def lunarArithmetric(a, op, b):
    print('  {0} {1} {2} ='.format(a,op,b), end=' ')
    res = ''
    if op == '+':
        suA, suB = int(a), int(b)
        while suA > 0 or suB > 0:
            res = str(max(suA%10, suB%10)) + res
            suA, suB = suA//10, suB//10
    else:
        nAB = len(a)+len(b)-1
        arAB = [0 for _ in range(nAB)]
        a = a[::-1]
        b = b[::-1]
        idx = 0
        while idx < len(b):
            for i in range(len(a)):
                arAB[idx+i] = max(arAB[idx+i], min(int(a[i]), int(b[idx])))
            idx += 1
        for i in range(nAB):
            res = str(arAB[i]) + res
    print(res)

2023/07/28 15:18

insperChoi

목록으로