첫 번째 계산
아이들은 여러 자리 숫자들을 더하기 위해서 우에서 좌로 숫자를 하나씩 차례대로 더 하라고 배웠다. 1을 한 숫자 위치에서 다음 자리로 더하기위해 이동하는 "한자리올림"연산을 많이 발견하는 것은 중요한 도전이 된다. 당신의 일은 교육자가 그들의 어려움을 평가하기 위하여, 덧셈 문제들의 각 집합에 대해서 한자리올림 연산들의 수를 계산하는 것이다.
입력
입력의 각 라인은 10개의 숫자들보다 미만인 양의 정수들 두 개를 포함한다. 입력의 마지막 라인은 0 0 을 포한한다.
출력
마지막을 제외한 입력의 각 라인에 대해서 당신은 두 숫자들을 더한 결과에서 한자리올림 연산들의 수를 아래 처럼 보여지는 형식으로 계산하여 출력해야 한다.
입력 샘플
123 456
555 555
123 594
0 0
출력 샘플
No carry operation.
3 carry operations.
1 carry operation.
215개의 풀이가 있습니다.
from math import log10
a,b = map(int,raw_input('? ').split())
while all((a,b)):
print sum([(lambda x : (a%x+b%x)/x)(10**(n+1)) for n in xrange(int(max(log10(a),log10(b)))+1)])
a,b = map(int,raw_input('? ').split())
Python 2.7.6 간단히 잘 짜여진 것 같군요 ^_^
숫자 두개를 더해서 9보다 클때와 이전 숫자에서 하나 넘어올때를 계산했습니다...
def primary_arithmetic(num1, num2):
carry = 0
carry_sense = False
n1 = str(num1)
n2 = str(num2)
for i in range(1, len(n1)+1):
if (int(n1[-i]) + int(n2[-i]) > 9) or (int(n1[-i]) + int(n2[-i]) > 8 and carry_sense == True) :
carry += 1
carry_sense = True
else : carry_sense = False
if carry == 0: return "No"
return carry
print(primary_arithmetic(234, 769), "carry operation.")
Clojure로 작성했습니다. 짧게 쓰지 못해 아쉽네요.
질문과 샘플 데이터에서 명시되지 않은 조건이 있어서 이렇게 처리했습니다.
508 + 12의 경우와 같이 두 수의 자리수 크기가 다른 경우도 계산함.
678 + 322 = 1000의 경우('자리 넘김'이 3번 일어남)와 같이, 다음 자리로 넘어간 수를 반영해 계산함.
(defn count-pa
[[n1 n2]]
(let [parse #(Integer/parseInt (str %))
size (max (count n1) (count n2))
fill-0 #(into (repeat (- size (count %))
0)
%)
n1 (-> (map parse n1) fill-0)
n2 (-> (map parse n2) fill-0)]
(loop [d1 (first n1)
d2 (first n2)
d3 0
n1 (rest n1)
n2 (rest n2)
r 0]
(cond (empty? n1) (if (<= 10 (+ d1 d2 d3))
(inc r)
r)
(<= 10 (+ d1 d2 d3)) (recur (first n1) (first n2) 1 (rest n1) (rest n2) (inc r))
true (recur (first n1) (first n2) 0 (rest n1) (rest n2) r)))))
(defn check
[s]
(let [lines (clojure.string/split-lines s)
n-pairs (map #(re-seq #"[\d]+" %) lines)
results (map count-pa n-pairs)
to-result-str #(cond (zero? %) "No carry operation."
(= 1 %) "1 carry operation."
true (format "%s carry operations." %))]
(apply str (interpose "\n" (map to-result-str results)))))
void primaryArithmetic(int x, int y) {
int count = 0;
while(x >= 1 && y >= 1) {
if((x % 10 + y % 10) >= 10) {
count++;
}
x = x / 10;
y = y / 10;
}
if(count == 0) System.out.println("No carry operation.");
else System.out.println(count + " carry operation.");
}
java
#include<stdio.h>
int carry(int a,int b);
int main()
{
int count;
int one,two;
scanf("%d",&one);
scanf("%d",&two);
count= carry(one,two);
if(count==0)
{
printf("No carry operation\n");
}
else
{
printf("%d carry operations\n.",count);
}
}
int carry(int a,int b)
{
int count=0;
int i,tmp;
for(i=10;a>0&&b>0;)
{
tmp=(a%i+b%i);
if(tmp>=10)count++;
a=a/i;
b=b/i;
}
return count;
}
import java.util.ArrayList;
import java.util.Scanner;
public class PrimaryArithmetic {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strInput = input.nextLine();
ArrayList<String> strInputList = new ArrayList<String>();
while(!strInput.equals("0 0")){
strInputList.add(strInput);
strInput = input.nextLine();
}
int size = strInputList.size();
for(int i=0;i<size;i++){
processStr(strInputList.get(i));
}
}
private static void processStr(String listItem) {
String[] strNumbers = listItem.split(" ");
fillZero(strNumbers);
printResult(strNumbers);
}
private static void fillZero(String[] strNumbers) {
int maxSize = Math.max(strNumbers[0].length(), strNumbers[1].length());
strNumbers[0] = String.format("%0"+maxSize+"d", Integer.parseInt(strNumbers[0]));
strNumbers[1] = String.format("%0"+maxSize+"d", Integer.parseInt(strNumbers[1]));
}
private static void printResult(String[] strNumbers) {
String result = "No";
int nSize = strNumbers[0].length();
int cnt = 0;
int pNum = 0;
for(int i=0;i<nSize;i++){
int a = (int)strNumbers[0].charAt(nSize-1-i) - 48;
int b = (int)strNumbers[1].charAt(nSize-1-i) - 48;
if(a+b+pNum > 9){
cnt++;
pNum = 1;
}else{
pNum = 0;
}
}
if(cnt != 0)
result = ""+cnt;
System.out.println(result + " carry operation.");
}
}
Java로 나름대로 해봤어요 괜찮은가요?^^
package h12_primary_arithmatic;
import java.util.Scanner;
public class PrimaryArithmatic {
public static void main(String[] args) {
Scanner num=new Scanner(System.in);
int in1, in2, r1, r2, temp=0, result=0;
in1=num.nextInt(); in2=num.nextInt(); //값을 입력받음
for(int m=1; in1/m!=0 || in2/m!=0 ; m*=10){
r1=(in1/m)%10; r2=(in2/m)%10;
if((r1+r2+temp)>=10){ result++; temp=1; }
else temp=0;
}//요기부터 출력
if(result>0) System.out.print(result);
else System.out.print("No");
System.out.print(" carry operation");
if(result>1) System.out.print("s");
System.out.print(".");
}
}
int GetCarryCount(int nX,int nY,int nCarry)
{
int nTemp = (nX%10 + nY %10 + nCarry) /10;
if(nX == 0 || nY == 0)
{
if(nCarry ==0)
return nTemp;
}
return nTemp + GetCarryCount(nX/10,nY/10,nTemp );
}
int _tmain(int argc, _TCHAR* argv[])
{
while(1)
{
int nX,nY,nCarry;
printf("?");
scanf(("%d %d"),&nX,&nY);
printf("%d Carry\n ",GetCarryCount(nX,nY,0));
}
return 0;
}
Ruby
def count_carry(a, b)
[a, b].map{|i|i.to_s.scan(/./).reverse}
.inject(&:zip)
.map{|i|i.map(&:to_i).inject(:+)}
.inject([0, 0]){|s, i| [i + s[0] > 9 ? 1 : 0, i + s[0] > 9 ? s[1] + 1 : s[1]]}
.last
end
def process(str)
str.each_line.to_a
.map(&:strip)
.slice_before(/0 0/).to_a[0]
.map{|i| c = count_carry(*i.split(" ")); (c > 0 ? c.to_s : "No") + " carry operation."}
.join("\n")
end
Test
require 'test/unit'
extend Test::Unit::Assertions
assert_equal process("123 456\n555 555\n123 594\n0 0"), "No carry operation.\n3 carry operation.\n1 carry operation."
파이썬입니다.
val = str(input("input value: "))
_list = val.split(" ")
byMax = 0
if len(_list[0]) > len(_list[1]):
byMax = len(_list[0])
else:
byMax = len(_list[1])
_list[0] = '%0*d' % (byMax,int(_list[0]))
_list[1] = '%0*d' % (byMax,int(_list[1]))
addNum = 0
sumCarry = 0
for ix,x in enumerate(_list[0]):
if int(x) + int(_list[1][ix]) > 9:
addNum = 1
sumCarry = sumCarry + 1
else:
addNum = 0
print('%s carry operation.' % "No" if sumCarry == 0 else sumCarry)
clojure
(defn str-rev
" reverse string number.
# (str-rev \"1234\")
# ;=> (4 3 2 1)
"
[num-str]
(->> num-str
(map #(Character/getNumericValue %))
reverse))
(defn primary-arithmetic [a-str b-str]
(loop [a-rev (str-rev a-str)
b-rev (str-rev b-str)
carry 0
carry-count 0]
(let [[a & ast] a-rev
[b & bst] b-rev]
(if (and (nil? a) (nil? b))
carry-count
(let [a (if (nil? a) 0 a)
b (if (nil? b) 0 b)]
(if (>= (+ a b carry) 10)
(recur ast bst 1 (inc carry-count))
(recur ast bst 0 carry-count)))))))
(for [[a-str b-str] [["123" "456"]
["555" "555"]
["123" "594"]
["999" "1"]]]
(primary-arithmetic a-str b-str))
a=input('INPUT first num : ')
b=input('INPUT second num : ')
c=len(a)
lendif=abs(len(a)-len(b))
carry=0
put_on=1
if len(a) == len(b):
for i in range(0,c):
if int(a[c-1-i])+int(b[c-1-i])+put_on>=10:
carry+=1
elif len(a) > len(b):
for i in range(0,c):
if int(a[c-1-i])+int(b[c-1-lendif-i])+put_on>=10:
carry+=1
else:
for i in range(0,c):
if int(a[c-1-i])+int(b[c-1+lendif-i])+put_on>=10:
carry+=1
print(carry,'carry operation')
자릿수 다른 계산도 포함하였습니다. put_on은 한 자릿수의 계산이 이전 자릿수에 의해 영향을 받는 경우를 고려한 것 입니다. 예를 들어 654+343과 같은 경우인데요, 영향을 받지 않는 경우에 put_on 을 더해도 결과 값에는 영향을 미치지 않기에(9+9+1의 값이 20이 안되기에) 영향에 상관 없이 put_on을 더하게 하였습니다.
Javascript 입니다.
간단히 생각해봤습니다. 그냥 사람이 직접 계산하는걸 생각해봤습니다. 뒷자리부터 계산하면 손쉬울 것 같더군요. 자릿수 다른 케이스, 자릿수 변경이 일어난 경우 해당 결과를 다음 게산시에 반영되도록 하였습니다 (222+778 = 1000이 되는 케이스)
재미있었던 문제였습니다 ㅎㅎ
var str = "123 594".split(" "),
a = str[0].split("").reverse().join(""), b = str[1].split("").reverse().join(""), c = 0;
for(var i = 0 ; i < Math.max(a.length, b.length) ; i++)
if(((+a[i] || 0) + (+b[i]) || 0) >= 10) { a = a.substr(0, i+1) + (+a[i+1]+1 + "") + a.substr(i+2); c++; }
console.log((c ? c : 'No') + " carry operation" + (c > 1 ? "s." : "."));
1 carry operation.
var str = "123 594".split(" "), // 입력값을 받고 공백을 기준으로 배열로 쪼갭니다. [123, 594] 형태의 배열이 나오겠죠.
a = str[0].split("").reverse().join(""), // 뒷자리부터 계산하기 위해서 뒤집습니다.
b = str[1].split("").reverse().join(""), // 뒷자리부터 계산하기 위해서 뒤집습니다.
c = 0; // 카운팅용 변수입니다.
for(var i = 0 ; i < Math.max(a.length, b.length) ; i++) { // 자릿수가 다른 케이스를 맞추기 위해 두 비교값 중 자릿수가 긴 것을 기준으로 삼습니다.
// 현재 뒤집은 숫자들이 string 데이터형이기때문에 각 자릿수를 배열 다루듯이 접근할 수 있습니다. 이걸 활용해봅시다.
// 각 자릿수 계산을 하기 위해선 Number형으로 타입캐스팅을 하는게 안전한 것 같아서 +a[i]와 같이 트릭을 써서 타입캐스팅합니다.
// 자릿수가 다른 상황에서 각 숫자를 접근하는 경우 undefined가 반환될 수 있으므로 or (||) 연산자를 통해 undefined인 경우 0으로 처리합니다.
if(((+a[i] || 0) + (+b[i]) || 0) >= 10) { // 만약 자릿수 변경이 일어나는 경우 10 이상인 케이스겠죠.
a = a.substr(0, i+1) + (+a[i+1]+1 + "") + a.substr(i+2); // 다음 자릿수에 1을 더하고 문자열로 다시 저장합니다.
c++; // 그리고 카운팅합니다.
}
}
console.log((c ? c : 'No') + " carry operation" + (c > 1 ? "s." : ".")); // 출력입니다.
public String primaryArithmeticint num1, int num2){
//입력받은 num1, num2를 string으로 변환하고, 뒤집습니다.
String str1 = Util.reverse(Integer.toString(num1));
String str2 = Util.reverse(Integer.toString(num2));
int carryCnt = 0, i = 0, sum = 0, carry = 0;
// 758 + 55555 이렇게 자리수가 바뀐 경우의 수를 대비하여 짧은 숫자 길이만큼 loop가 돌도록 변수를 정의했습니다.
int loopCnt = ( (str1.length() - str2.length()) < 0 ) ? str1.length() : str2.length();
// loop를 돌면서 계산합니다 요리조리.
while(i < loopCnt){
sum = Character.getNumericValue(str1.charAt(i)) + Character.getNumericValue(str2.charAt(i)) + carry;
if(sum >= 10){
carryCnt++;
carry = 1;
}else {
carry = 0;
}
i++;
}
return carryCnt==0 ? "NO carry" : carryCnt + " carry!!";
}
// 여기까지가 풀이이고,
// Util 클래스는 String을 거꾸로 뒤집는거 구현해놓은거에요 ㅠㅋ
public class Util {
public static String reverse(String str) {
StringBuilder reverse = new StringBuilder();
int i = str.length();
while(i != 0){
reverse.append(str.charAt(--i));
}
return reverse.toString();
}
}
Java로 작성했는데 위에 풀이들 보니까 깔끔한 풀이들 많네요 보고 많이 배워갑니다 이상한거 있으면 지적도 부탁드려요 !! (수련중... )
Swift로 작성했고 재귀함수로 풀었습니다.
var num1Array:Array<Int> = [644, 455, 123, 0]
var num2Array:Array<Int> = [456, 555, 594, 0]
let numCount:Int = num1Array.count
func calcNumbers(num1:Int, num2:Int) -> Int {
var number1 = num1
var number2 = num2
if (number1 != 0) && (number2 != 0) {
let tmpNum1 = number1 % 10
let tmpNum2 = number2 % 10
if ((tmpNum1 + tmpNum2) >= 10) {
return 1 + calcNumbers((number1/10)+1, number2/10)
} else {
return calcNumbers(number1/10, number2/10)
}
} else {
if num1 >= 10 {
return 1
}
}
return 0
}
func printResult(result:Int) -> Void {
var str:String?
if result > 0 {
str = "\(result) carry operations."
} else {
str = "No carry operation."
}
println(str)
}
for i in 0..numCount {
var result = num1Array[i] > num2Array[i] ? calcNumbers(num1Array[i], num2Array[i]) : calcNumbers(num2Array[i], num1Array[i])
printResult(result)
}
파이썬 입니다.
짜고 보니 기네요, 아직 내공 부족으로... 다른 분들 올려놓으신 걸 열심히 살펴봐야겠습니다.
input_list=[] # input을 받아서 리스트 형태 전환합니다.
stopword = "0 0"
while True:
line = input()
line_list = line.split(" ")
if line.strip() == stopword:
break
input_list.append(line_list)
def plus(one, two): # 두개의 input을 받아서 carry operation 수를 계산.
num_list_one = list(one)
num_list_two = list(two)
num_list_one.reverse() # 뒷자리부터 계산하기 위해 순서를 뒤집었습니다.
num_list_two.reverse()
plus_len = min(len(num_list_one),len(num_list_two))
carry_count = 0
carry_over = 0
for x in range (plus_len):
one_temp = int(num_list_one[x])
two_temp = int(num_list_two[x])
temp_sum = one_temp + two_temp + carry_over
if temp_sum >= 10:
carry_count = carry_count + 1
carry_over = 1
else:
carry_over = 0
return carry_count
for data in input_list: # 위의 plus 함수를 실행하고 결과를 출력
carry_count = plus(data[0], data[1])
if carry_count == 0:
print("No carry operation.")
elif carry_count == 1:
print("1 carry operation.")
else:
print("%d carray operations."%carry_count)
// C# 입니다.
using System;
class Program
{
static void Main()
{
string output = "\n출력 샘플\n";
while (true)
{
string[] tokens = Console.ReadLine().Split();
int a = int.Parse(tokens[0]);
int b = int.Parse(tokens[1]);
if (a == 0 && b == 0)
{
break;
}
int big, small;
if (a - b > 0)
{
big = a;
small = b;
}
else
{
big = b;
small = a;
}
int carryCount = 0;
int carry = 0;
while (small > 0)
{
int sum = (big % 10) + (small % 10) + carry;
if (sum > 9)
{
carryCount++;
carry = sum / 10;
}
big /= 10;
small /= 10;
}
output += (carryCount == 0) ? "No " : carryCount + " ";
output += "Carry Operation.\n";
}
Console.WriteLine(output);
}
}
python 2.7
import unittest
def pa(src):
left, right = src.split()
max_len = max(len(left), len(right))
carry = 0
next_carry = 0
for i in range(1, max_len+1):
lc, rc = 0, 0
if i <= len(left): lc = int(left[-i])
if i <= len(right): rc = int(right[-i])
if lc + rc + next_carry >= 10:
next_carry = 1
else:
next_carry = 0
carry += next_carry
return carry
class MyTest(unittest.TestCase):
def test1(self):
self.assertEquals(0, pa("123 456"))
self.assertEquals(3, pa("555 555"))
self.assertEquals(1, pa("123 594"))
self.assertEquals(3, pa("544 456"))
self.assertEquals(4, pa("9544 456"))
self.assertEquals(6, pa("999544 456"))
self.assertEquals(7, pa("19999544 456"))
if __name__ == "__main__":
unittest.main()
의외로 생각할 거리가 많은 문제였네요. 서로 다른 자리수의 경우도 체크 해 봤습니다.
python 입니다. 111+889(=1000) 처럼 이전 자리수 영향으로 자리올림 되는 것까지 고려했습니다.
import unittest
def func(n1, n2, carry=0, puton=0):
for i in range(1, min(len(str(n1)), len(str(n2)))+1):
if (int(n1[-i]) + int(n2[-i]) + puton) >= 10 : carry += 1
if (int(n1[-i]) + int(n2[-i]) + puton) == 10 : puton = 1
else: puton = 0
return carry
class Test(unittest.TestCase):
def test1(self):
self.assertEqual(0, func('123', '456'))
self.assertEqual(3, func('555', '555'))
self.assertEqual(1, func('123', '594'))
self.assertEqual(3, func('111', '889'))
if __name__ == "__main__":
unittest.main()
자리넘김이 2번일어나는 경우는 커버합니다만, 3자리수만 처리 합니다.
input = "123 456
555 555
123 594
678 322
0 0"
class Sum
attr_reader :a, :b
def initialize(a, b)
raise ArgumentError, "number size should 3" unless a.size == 3 && b.size == 3
@a = a
@b = b
end
def display
case carry_count
when 0 then "No carry operation."
when 1 then "1 carry operation."
else "#{carry_count} carry operations."
end
end
private
def carry_count
count = 0
carried = false
[2, 1, 0].each do |i|
carried = a[i].to_i + b[i].to_i + (carried ? 1 : 0) >= 10
count += 1 if carried
end
count
end
end
input.split("0 0").first.split("\n").each do |line|
a, b = line.split(" ")
puts Sum.new(a, b).display
end
coding by python beginner
inps = []
while True:
t0 = input().split()
inps.append(t0)
if t0 == ['0', '0']: break
for l in inps:
carry = ctotal = 0;
for i in range( len(l[0]) - 1, -1, -1):
carry = 1 if int(l[0][i]) + int(l[1][i]) + carry > 9 else 0
ctotal += carry
print( ( 'No' if ctotal == 0 else str(ctotal) ) + ' carry operations.')
Scala로 풀었습니다.
def countRoundUp(input: String): Int = {
def round(left: Int, right: Int, roundedUp: Int): Int =
(left + right + roundedUp) / 10
@annotation.tailrec
def fn(left: String, right: String, roundedUp: Int, count: Int): Int = {
(left, right) match {
case ("", "") => count
case (left, "") =>
val rUp = round(left.head.asDigit, 0, roundedUp)
fn(left.tail, "", rUp, count + rUp)
case ("", right) =>
val rUp = round(0, right.head.asDigit, roundedUp)
fn("", right.tail, rUp, count + rUp)
case (left, right) =>
val rUp = round(left.head.asDigit, right.head.asDigit, roundedUp)
fn(left.tail, right.tail, rUp, count + rUp)
}
}
val pattern = """(\d+) (\d+)""".r
input match {
case pattern("0", "0") => -1
case pattern(left, right) => fn(left.reverse, right.reverse, 0, 0)
case _ => throw new IllegalArgumentException
}
}
assert(countRoundUp("123 456") == 0)
assert(countRoundUp("555 555") == 3)
assert(countRoundUp("123 594") == 1)
assert(countRoundUp("19999544 456") == 7)
Scala로 다른 방식으로 구현했습니다.
def countRoundUp2(input: String): Int = {
def fn(ls: Seq[Int], rs: Seq[Int]): Int = {
val sums = ls.zipAll(rs, 0, 0).map{case (l, r) => l + r}
val (_, count) =
((0, 0) /: sums) { case ((roundedUp, count), sum) =>
val rUp = (roundedUp + sum) / 10
(rUp, count + rUp)
}
count
}
val pattern = """(\d+) (\d+)""".r
input match {
case pattern("0", "0") => -1
case pattern(left, right) =>
fn(left.reverse.map(_.asDigit), right.reverse.map(_.asDigit))
case _ => throw new IllegalArgumentException
}
}
assert(countRoundUp2("123 456") == 0)
assert(countRoundUp2("555 555") == 3)
assert(countRoundUp2("123 594") == 1)
assert(countRoundUp2("19999544 456") == 7)
C#으로 작성했습니다.
using System;
public void PrimaryArithmetic(string input1, string input2)
{
var small = input1.Length < input2.Length ? input1 : input2;
var large = input1.Length < input2.Length ? input2 : input1;
var sum = 0;
if (small.Length < large.Length)
{
var sub = large.Length - small.Length;
large = large.Substring(sub);
}
for(int i = 0; i < small.Length; i++)
if (int.Parse(small[i].ToString()) + int.Parse(large[i].ToString()) > 9)
sum++;
if (sum == 0) Console.WriteLine("No carry operation.");
else if (sum == 1) Console.WriteLine("1 carry operation.");
else Console.WriteLine(sum + " carry operations.");
}
public static string ReplaceHexadecimalSymbols(string inString)
{
string r = "[\x00-\x08\x0B\x0C\x0E-\x1F\x26]";
return Regex.Replace(inString, r, "", RegexOptions.Compiled);
}
Using python code가 지저분 해 보이네요..ㅠㅠ
#!/usr/bin/python
#! -*- coding: utf-8 -*-
def PrimeA():
a = 0
b = 0
while True:
cnt = 0
a = raw_input("")[::-1].split(" ")
if a[0] == "0" and a[1] == "0":
print "terminating..."
break
elif len(a[0]) >=10 or len(a[1]) >=10:
continue
if len(a[0]) >= len(a[1]):
for i in range(len(a[1])):
if int(a[0][i]) + int(a[1][i]) >=10:
cnt += 1
else:
for i in range(len(a[0])):
if int(a[0][i]) + int(a[1][i]) >=10:
cnt += 1
print str(cnt) + " carry operations detected."
if __name__=="__main__":
PrimeA()
#397.py
def surplus(y):
# count carry.
count=0
sur=0
# To use zip function, make artifical 0s in front of real input
l=abs(len(y[0])-len(y[1]))
y[0]="0"*l+y[0]
y[1]="0"*l+y[1]
for p,q in zip(y[0][::-1],y[1][::-1]):
if int(p)+int(q)+sur>9:
count+=1
sur=1
else:
sur=0
return count
f=open("input.txt","r")
inputs=f.readlines()
for x in inputs:
y=x.split(" ")
if y[0]==y[1]=='0':
break
else :
print y
print "%d carry " %surplus(y[0:2])
파이썬입니다.
Sub Main()
PhyPlus(123, 456)
PhyPlus(555, 555)
PhyPlus(123, 594)
Console.ReadLine()
End Sub
Public Function PhyPlus(a As String, b As String) As String
Dim r As New Text.StringBuilder, stack(0) As Integer
Dim lf As Boolean = (a.Length > b.Length)
Dim cnt As Integer = 0
ReDim stack(IIf(lf, a.Length, b.Length) - 1)
For i As Integer = 1 To Math.Abs(a.Length - b.Length)
If lf Then
b = "0" & b
Else
a = "0" & a
End If
Next
For i As Integer = a.Length To 1 Step -1
Dim aa As Integer = Mid(a, i, 1) + stack(i - 1)
Dim bb As Integer = Mid(b, i, 1)
Dim c As Integer = aa + bb
If i = 1 And c >= 10 Then cnt += 1
If c >= 10 And i > 1 Then
stack(i - 2) = c \ 10
cnt += 1
c = c Mod 10
End If
r.Append(StrReverse(c))
Next
Console.WriteLine("{0} carry operation{1}.", IIf(cnt = 0, "No", cnt), IIf(cnt > 1, "s", ""))
Return StrReverse(r.ToString)
End Function
예전에 만들어둿던 물리덧셈 함수를 이용해봤습니다.
무식하게 짰습니다. C입니다. 알고리즘은 실제로 걍 더한 수와 자리수끼리 더한 후 10으로 나눈 나머지를 자리수로 하는 수를 두개 구해서 그 수들간의 자리수의 차가 얼마나 나는지를 비교했습니다. 678 322 같이 실제 계산 값이 1000, 즉 자리수가 0이 나오는 경우는 자리수의 차를 구하면 음수가 나오므로 10을 다시 더해주었습니다.
#include <stdio.h>
#include <stdlib.h>
int power(int base, int index)
{
int i;
int result=1;
for(i=0;i<index;i++) result = result * base;
return result;
}
int getsize(int n)
{
int i=0;
int size;
while(1)
{
if (n%power(10,i)==n)
{
size = i;
break;
}
i++;
}
}
int *getdigits(int n)
{
int size;
size = getsize(n);
int *result;
result = (int *) malloc(sizeof(int)*size);
int i;
for(i=0;i<size;i++)
{
result[i] = n/power(10,size-i-1);
n = n%power(10,size-i-1);
}
return result;
}
int main()
{
int a,b,ncarry;
int *real;
int *nocarry;
int i;
while(1)
{
scanf("%d %d", &a, &b);
if (a+b==0) break;
real = getdigits(a+b);
/*
for(i=0;i<getsize(a+b);i++)
if (real[i]==0) real[i]=10;
*/
int asize = getsize(a);
int *adigits = getdigits(a);
int bsize = getsize(b);
int *bdigits = getdigits(b);
if (asize==bsize)
{
nocarry = (int *) malloc(sizeof(int)*asize);
for(i=0;i<asize;i++) nocarry[i]=(adigits[i]+bdigits[i])%10;
}
else if (asize>bsize)
{
nocarry = (int *) malloc(sizeof(int)*asize);
for(i=0;i<asize-bsize;i++) nocarry[i]=adigits[i];
for(i=0;i<bsize;i++) nocarry[i+asize-bsize] = (adigits[i+asize-bsize]+bdigits[i])%10;
}
else
{
nocarry = (int *) malloc(sizeof(int)*bsize);
for(i=0;i<bsize-asize;i++) nocarry[i]=bdigits[i];
for(i=0;i<asize;i++) nocarry[i+bsize-asize] = (bdigits[i+bsize-asize]+adigits[i])%10;
}
int ncarry=0;
int realsize = getsize(a+b);
int nocarrysize;
if (asize>bsize) nocarrysize = asize;
else nocarrysize = bsize;
if (realsize>nocarrysize)
{
ncarry = ncarry + real[0];
for(i=0;i<nocarrysize;i++)
{
ncarry = ncarry + real[i+1]-nocarry[i];
if (real[i+1]<nocarry[i]) ncarry = ncarry+10;
}
}
else
{
for(i=0;i<nocarrysize;i++)
{
ncarry = ncarry + real[i]-nocarry[i];
if (real[i]<nocarry[i]) ncarry = ncarry+10;
}
}
if (ncarry==0) printf("No carry operation.\n");
else if (ncarry==1) printf("1 carry operation.\n");
else printf("%d carry operations.\n", ncarry);
}
return 0;
}
static void exce11()// Primary Arithmetic
{
ArrayList<String> arrStr = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
boolean loop = true;
while (loop)
{
String str = scan.nextLine();
if (str.equals("0 0"))
loop = false;
else
arrStr.add(str);
}
for (int i = 0; i < arrStr.size(); i++)
{
String[] str = arrStr.get(i).split(" ");
int[] op = new int[2];
int up = 0;
int cnt = 0;
op[0] = Integer.parseInt(str[0]);
op[1] = Integer.parseInt(str[1]);
while (op[0] > 0 || op[1] > 0)
{
int sum = op[0] % 10 + op[1] % 10 + up;
if (sum >= 10)
{
up = 1;
cnt++;
} else
up = 0;
op[0] /= 10;
op[1] /= 10;
}
if(cnt == 0)
System.out.println("No carry operation.");
else
System.out.printf("%d carry operation.\n",cnt);
}
}
Python3입니다. 각 문자열을 뒤집고 첫번째 pair부터 carry가 발생하는지 확인하도록 구현하였습니다. 더하려는 두 숫자의 자릿수가 다른 경우를 감안하기 위해 앞에 '0'을 여러개 붙였습니다.
def getCarries(a, b):
carry = 0
cflag = 0
for (a1, b1) in zip(a[::-1], b[::-1]):
if (int(a1) + int(b1) + cflag > 9):
carry = carry + 1
cflag = 1
else:
cflag = 0
return carry
res = list()
while 1:
a, b = input().split(' ')
if a == '0': break
res.append(getCarries('0' * len(b) + a, '0' * len(a) + b))
for carries in res:
if carries == 0:
print("No carry operation.")
elif carries == 1:
print("1 carry operation.")
else:
print("%d carry operations." % carries)
def num2array(num):
# 숫자를 각 자리로 분리후, 낮은 자리수부터 반환
digit = list(str(num))[-1::-1]
numArray = [int(digit[x]) for x in range(len(digit))]
return numArray
if __name__ == '__main__':
while True:
Num = input('Enter two number: ')
Num = [int(x) for x in Num.split()]
# 0 0 입력시 종료
if Num == [0, 0]:
break
Num1 = num2array(Num[0])
Num2 = num2array(Num[1])
carry = 0
count = 0
# 몇 번의 올림연산 발생하는지 카운트
for x in range(min(len(Num1),len(Num2))):
if divmod(Num1[x] + Num2[x] + carry,10)[0] == 1:
count += 1
carry = 1
else:
carry = 0
# 자릿수가 다른 숫자에 대해 처리
if len(Num1) > len(Num2):
count += divmod(Num1[len(Num2)] + carry,10)[0]
elif len(Num1) < len(Num2):
count += divmod(Num2[len(Num1)] + carry,10)[0]
if count:
print('%d carry operations.' % count)
else:
print('No carry operation.')
입력된 숫자의 자릿수가 다른 경우까지 고려해봤습니다. 파이썬 3.0
python 3.4
count =0
inum = input()
a,b = inum.split()
c=str(int(a) + int(b))[::-1]
a=a[::-1]
b=b[::-1]
for i in range(len(a)):
if c[i]<max(b[i],a[i]): count+=1
print("%d carry operation"%count)
캐리아웃이 발생한다면 즉, 6+7이면 결과 13의 1의 자리수는 무조건 더하는 수의 최대값(7)보다 작습니다.이를 이용해서 구성했습니다.
inputs = []
while True:
m,n = raw_input().split()
m = int(m)
n = int(n)
if m==0 and n ==0 : break
inputs.append((m,n))
for (x,y) in inputs:
x = [int(n) for n in str(x)];x.reverse()
y = [int(n) for n in str(y)];y.reverse()
c = [0]*(max(len(x),len(y))+1)
for i in range(min(len(x),len(y))):
if x[i]+y[i]+c[i] > 9 : c[i+1] = 1
carry = c.count(1)
if carry == 0 : carry = 'No'
print carry, 'carry operations'
Python 3
while True:
A, B = input("Input 2 numsbers or 0 0 for quit : ").split()
if A != "0" or B != "0":
print("%d carry operation." % len([i for i in range(1, min(len(A), len(B))+1) if (int(A[-i:])+int(B[-i:])) >= 10**i]))
else:
break
결과
123 456
0 carry operation.
555 555
3 carry operation.
123 594
1 carry operation.
0 0
while __name__ == '__main__':
li = []
while 1:
tmp = list(map(int, (input('입력: ').split())))
if tmp == [0,0]:break
else:li.append(tmp)
for x in range(len(li)):
v = 0
for j in range(min(len(str(i)) for i in li[x])):
a = int(str(li[x][0])[-j-1])
b = int(str(li[x][1])[-j-1])
if a+b>=10:v+=1
s = ''
if v > 1:s = 's'
if v == 0:v = 'No'
print('{0} carry operation{1}'.format(v,s))
파이썬 3.5.1 입니다.
Ruby
cnt_cr = ->a,b,cr=[0] { a+b > 0 ? cnt_cr[a/10, b/10, cr << (a%10 + b%10 + cr[-1]) / 10] : cr.sum }
prt = ->nums,n=cnt_cr[*nums] { puts "%s carry operation%s." % [n > 0 ? n : "No", n > 1 ? "s" : ""] }
chk_cr = -> { gets("0 0").split.map(&:to_i).each_slice(2).to_a[0..-2].each &prt }
Test
$stdin = StringIO.new("123 456\n555 555\n123 594\n0 0\n")
carry_output = "No carry operation.\n3 carry operations.\n1 carry operation.\n"
expect{ chk_cr.call }.to output(carry_output).to_stdout
Output
123 456
555 555
123 594
12 345
123 99
0 0
No carry operation.
3 carry operations.
1 carry operation.
No carry operation.
2 carry operations.
import itertools
while 1:
a, b = input().split()
if a == '0' and b == '0':
break
a, b = a[::-1], b[::-1]
c = [int(a) + int(b) for a, b in itertools.zip_longest(a, b, fillvalue='0')]
n = 0
carry = 0
for i in c:
if i + n >= 10:
carry += 1
n = 1
else:
n = 0
print('{} carry operation{}.'.format(carry if carry else 'No', 's' if carry > 1 else ''))
999999999999999999999 + 1 같은 케이스가 있어서 자리수를 긴쪽에 맞추고 뒤에서 부터 더해봤습니다.
def do(s):
carry, flag = 0, 0
a, b = sorted(s.split(' ')[:2], key=len, reverse=True)
b = "0" * (len(a) - len(b)) + b
samples = zip(a[::-1], b[::-1])
for s in samples:
(carry, flag) = (carry+1, 1) if int(s[0]) + int(s[1]) + flag > 9 else (carry, 0)
print("{} carry operation{}".format(carry if carry > 0 else "No", "s" if carry > 1 else ""))
data = []
while True:
a = input().strip()
if a.strip() == '0 0':
break
else:
data.append(a)
for d in data:
do(d)
a,b=input().split(" ")
carry=0
ca=[]
while a!="0" or b!="0":
c=str(int(a)+int(b))
for i in range(min(len(a),len(b))+1):
if int(a[-i])+int(b[-i])!=int(c[-i]):
carry=carry+1
minab=str(min(int(a),int(b)))
maxab=str(max(int(a),int(b)))
if c[-len(minab)-1]!=maxab[-len(minab)-1]:
carry=carry+1
ca.append(carry)
carry=0
a, b = input().split(" ")
print("No carry operation")
for i in ca:
print("%d carry operation" %i)
Python 3.4.4
def carry_operation(a, b):
if a == 0 and a == b:
exit()
a_list = a[::-1]
b_list = b[::-1]
count = 0
for i in range(len(a_list)):
if int(a_list[i]) + int(b_list[i]) > 9:
count += 1
print(count, 'carry operation.')
while True:
a, b = input().split(" ")
carry_operation(a, b)
package main
import (
"fmt"
)
func main() {
var n1, n2 int
for {
fmt.Scan(&n1, &n2)
if n1 == 0 && n2 == 0 {
break
}
carry := false
carry_count := 0
for n1 != 0 || n2 != 0 {
v1 := n1 % 10
n1 /= 10
v2 := n2 % 10
n2 /= 10
sum := v1 + v2
if carry {
sum++
}
carry = false
if sum >= 10 {
carry = true
carry_count++
}
}
fmt.Println(carry_count, "carry operation.")
}
}
#include <iostream>
#include <vector>
int is_carry(int, int);
int main(void)
{
std::vector <int> vec1, vec2;
int input1, input2, ret;
do {
std::cin >> input1 >> input2;
std::cin.ignore(1, ' ');
vec1.push_back(input1);
vec2.push_back(input2);
} while (input1 != 0 && input2 != 0);
vec1.pop_back(); vec2.pop_back();
for (int i = 0; i < vec1.size(); i++) {
ret = is_carry(vec1[i], vec2[i]);
if (ret == 1)
std::cout << "1 carry operation." << std::endl;
else if (ret > 1)
std::cout << ret << " carry operations." << std::endl;
else
std::cout << "No carry operation." << std::endl;
}
return 0;
}
int is_carry(int num1, int num2) {
int n1 = num1, n2 = num2, calc = 0, carry = 0;
while (n1 != 0 || n2 != 0) {
calc = ((n1 % 10) + (n2 % 10) + calc) / 10;
if (calc == 1)
carry++;
n1 /= 10; n2 /= 10;
}
return carry;
}
input_list=[]
while 1:
input_list+=[str(input("input \n >> "))]
if input_list[-1]=='0 0' : break
carry=[]
count = 0
input_list.pop(-1)
for i in input_list:
carry+=[0]
i=" ".join(i).split()
i.reverse()
for j in range(3):
if int(i[j])+int(i[j+3])>=10 :
i[j+1]=eval(i[j+1]+'+1')
carry[count]+=1
count+=1
for i in carry:
if i == 0:
print("No carry operations")
else:
print("%d carry operations"%i)
Python 3.5.2 222 778의 케이스를 고려하지 않았다가 깜짝 놀랐네요
123 456 123 594 555 555 222 778
No carry operations 1 carry operations 3 carry operations 3 carry operations
#include <stdio.h>
int pow(int a, int b);
void main(void) {
int input[10][2];
int count = 0;
for(int i = 0 ; i < 10; i++) {
scanf("%d %d",&input[i][0], &input[i][1]);
if(input[i][0] == 0 && input[i][1] ==0)
break;
count++;
}
int carry = 0;
for(int i = 0; i < count;i++) {
for(int j = 10 ; j > 0 ;j--) {
if(input[i][0]/pow(10, j) + input[i][1]/pow(10, j) >= 10) {
carry++;
}
input[i][0] = input[i][0]%pow(10, j);
input[i][1] = input[i][1]%pow(10, j);
if(input[i][1] < 10 && input[i][0] < 10 && input[i][1] + input[i][0] >=10)
carry++;
}
if(carry == 0)
printf("No carry operation\n");
else
printf("%d carry operation\n", carry);
carry = 0;
}
}
int pow(int a, int b) {
int temp = a;
for(int i = 1; i < b ;i++)
a=a*temp;
return a;
}
import unittest
def pa(line):
cnt = 0
a,b = line[0][::-1], str(int(line[0]) + int(line[1]))[::-1]
for i in range(len(str(a))):
if int(a[i]) > int(b[i]):
cnt+=1
return cnt
class myTest(unittest.TestCase):
def test1(self):
self.assertEqual(0, pa(["123", "456"]))
self.assertEqual(3, pa(["555", "555"]))
if __name__ == '__main__':
unittest.main()
'''
lines=[]
while True:
temp = input().split(' ')
if temp[0] == temp[1] == '0':
break
lines.append(temp)
for line in lines:
print(line)
print(pa(line))
'''
unittest를 써봤습니다.
def input_():
list_N = []
while 1:
input_N = input()
if (input_N == '0 0'):
break
input_N_D = tuple(map(int, input_N.split()))
list_N.append(input_N_D)
return list_N
def Primary_A(Number_1, Number_2):
Carry_N = 0
a = 0
quotient_1 = Number_1
quotient_2 = Number_2
while(quotient_1 != 0 and quotient_2 != 0):
if(((quotient_1 % 10) + (quotient_2 % 10) + a ) >= 10 ):
a = 1
Carry_N = Carry_N + 1
else:
a = 0
quotient_1 = int(quotient_1 / 10)
quotient_2 = int(quotient_2 / 10)
if ((quotient_1 == 9 or quotient_2 == 9 ) and a == 1):
Carry_N = Carry_N + 1
return Carry_N
def output_(Carry_N):
if (Carry_N == 0):
print("No carry operation")
else:
print (str(Carry_N) + " carry operation")
list_N = input_()
for x in list_N:
Number_1 = x[0]
Number_2 = x[1]
Carry_N = Primary_A(Number_1, Number_2)
output_(Carry_N)
각 수를 string으로 보는 게 아니라 자연수로 보고 자릿수를 직접 구해서 값을 구했습니다. 999 11, 773 228 같은 경우도 계산 가능합니다
def do(in_):
in_ = in_.strip().split('\n')
for i in in_:
a = i.strip().split(' ')
if a.count('0') == len(a):
break
maxLen = max(map(len, a))
a = [('{:0>' + str(maxLen) + '}').format(x) for x in a]
tot = 0
c = 0
for x in zip(*[y[::-1] for y in a]):
v = sum(map(int, x)) + c
tot += 1 if v >= 10 else 0
c = v // 10
print('{} carry operation{}.'.format('No' if tot == 0 else tot
,'s' if tot > 1 else ''))
do("""
123 456
555 555
123 594
1182 818
0 0
""")
Python 3.5.2에서 작성하였습니다.
def input_():
list_N = []
while 1:
input_N = input()
if (input_N == '0 0'):
break
input_N_D = tuple(map(int, input_N.split()))
list_N.append(input_N_D)
return list_N
def Primary_A(Number_1, Number_2):
Carry_N = 0
a = 0
quotient_1 = Number_1
quotient_2 = Number_2
while(quotient_1 != 0 and quotient_2 != 0):
if(((quotient_1 % 10) + (quotient_2 % 10) + a ) >= 10 ):
a = 1
Carry_N = Carry_N + 1
else:
a = 0
quotient_1 = int(quotient_1 / 10)
quotient_2 = int(quotient_2 / 10)
if ((quotient_1 == 9 or quotient_2 == 9 ) and a == 1):
Carry_N = Carry_N + 1
return Carry_N
def output_(Carry_N):
if (Carry_N == 0):
print("No carry operation")
else:
print (str(Carry_N) + " carry operation")
list_N = input_()
for x in list_N:
Number_1 = x[0]
Number_2 = x[1]
Carry_N = Primary_A(Number_1, Number_2)
output_(Carry_N)
nums = list()
while nums == [] or nums[-1] != ['0','0']:
nums += [input().split(' ')]
for result in [sum([1 for y in range(len(num[0])) if len(str(int(num[0][y])+int(num[1][y]))) > 1]) for num in nums if num != ['0','0']]:
print(result,'carry operation.')
#### 2016.12.18 D-431 ####
python 2.7.xx
sample = “123 456”
res = sample.split(" ")
pairs = zip(res[0],res[1])
result = [ x for x in pairs if (int(x[0]) + int(x[1])) >= 10]
print "{} carry operation".format(len(result))
zip 으로 pairs 쌍으로 묶어주는게 뽀인트입니다
def checkCarry(a, b):
carryCount = 0
carryOne = 0
for i in range(len(a) if len(a)>len(b) else len(b)):
try:
numA = int(a[-(i+1)])
except:
numA = 0
try:
numB = int(b[-(i+1)])
except:
numB = 0
if (numA + numB + carryOne) >= 10:
carryCount += 1
carryOne = 1
else:
carryOne = 0
return carryCount
input = raw_input().split(" ")
while input[-1] != '0' and input[-2] != '0':
input += (raw_input().split(" "))
for i in range(0, len(input)-2, 2):
carryOperation = checkCarry(input[i], input[i+1])
if carryOperation == 0:
print("No carry operation.")
elif carryOperation == 1:
print("1 carry operation.")
else:
print("%d carry operations." % carryOperation)
파이썬으로 작성했습니다.
package codingdojang;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.StringBuffer;
public class Number11 {
public static void main(String args[]) {
int carryOperation;
ArrayList<Long> input = new ArrayList<Long>();
Scanner scan = new Scanner(System.in);
while(true) {
input.add(scan.nextLong());
if (input.get(input.size()-1) == 0 && input.get(input.size()-2) == 0)
break;
}
scan.close();
for (int i = 0; i < input.size() - 2; i += 2) {
carryOperation = checkCarry(input.get(i), input.get(i+1));
System.out.println(carryOperation);
}
}
private static int checkCarry(Long a, Long b) {
int numA, numB;
int carryCount = 0;
int carryOne = 0;
StringBuffer strReverseA = new StringBuffer(String.valueOf(a)).reverse();
StringBuffer strReverseB = new StringBuffer(String.valueOf(b)).reverse();
int maxLength = strReverseA.length() > strReverseB.length() ? strReverseA.length() : strReverseB.length();
for (int i = 0; i < maxLength; i++) {
try {
numA = Character.getNumericValue(strReverseA.charAt(i));
} catch(java.lang.StringIndexOutOfBoundsException e) {
numA = 0;
}
try {
numB = Character.getNumericValue(strReverseB.charAt(i));
} catch(java.lang.StringIndexOutOfBoundsException e) {
numB = 0;
}
if (numA + numB + carryOne >= 10) {
carryCount++;
carryOne = 1;
} else {
carryOne = 0;
}
}
return carryCount;
}
}
자바로 작성했습니다.
파이썬 2.7
s1, s2 = raw_input('?').split()
count = 0
i = 0
while(s1 is not '0' and s2 is not '0'):
for n in range(len(s1)):
if int(s1[n]) + int(s2[n]) > 9:
count += 1
print count, "carry operations"
count = 0
s1, s2 = raw_input('?').split()
Lee SunYeop님 것 참고했습니다.
def carry_op(dataa):
for data in dataa:
if data[0]!=0:
data[0]=list(str(data[0]))
data[1]=list(str(data[1]))
n,m=0,0
for i in range(-1,-4,-1):
if int(data[0][i])+int(data[1][i])+m>=10:
n+=1
m=1
else:
m=0
print(n)
carry_op([[123,456],[555, 555],[123,594],[0,0]])
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import static java.lang.System.in;
public class PrimaryArithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner(in);
List<String[][]> l = new ArrayList();
while (true) {
String f = sc.next();
String s = sc.next();
if (f.equals("0") && s.equals("0")) break;
String a[] = f.split("");
String b[] = s.split("");
String c[][] = new String[2][10];
Arrays.fill(c[0], "0");
Arrays.fill(c[1], "0");
System.arraycopy(a, 0, c[0], 10 - a.length, a.length);
System.arraycopy(b, 0, c[1], 10 - b.length, b.length);
l.add(c);
}
for (String[][] s : l) {
int c = 0;
int d = 0;
for (int i = 9; i >= 0; i--) {
int a = Integer.valueOf(s[0][i]);
int b = Integer.valueOf(s[1][i]);
if (a + b + d >= 10) {
d = 1;
c++;
}
}
if (c == 0)
System.out.println("No carry operation.");
else
System.out.println(c + " carry operations.");
}
}
}
int main(void)
{
for (;;)
{
int num1 = 0, num2 = 0;
int count = 0;
printf("정수를 입력하세요\n");
scanf_s("%d %d", &num1, &num2);
if (num1 == 0 && num2 == 0)
return 0;
int arr1[10] = {};
int arr2[10] = {};
int upnum[10] = {};
for (int i = 0; i < 10; i++)
{
if (num1 == 0 && num2 == 0)
break;
arr1[i] = num1 % 10;
num1 /= 10;
arr2[i] = num2 % 10;
num2 /= 10;
}
for (int i = 0; i < 5; i++)
{
if (arr1[i] + arr2[i] + upnum[i] >= 10)
{
count++;
upnum[i + 1] = 1;
}
}
printf("%d carry operation \n", count);
}
}
while 1:
cnt=0
n,m=input().split()
n=list(n)
size_n=len(n)
if n[0] =="0" and m[0]=="0":
break
else:
for i in range(size_n):
if int(n[i])+int(m[i])>9:
cnt+=1
if cnt==0:
print("No carry operation. ")
else :
print(cnt," carry operations.")
python 6.5, 그냥 for loop 함수, 계산은 역순이므로 reversed(range(3))
def carry_over(l):
up, cnt = 0, 0
for i in reversed(range(3)):
if int(l[0][i])+int(l[1][i])+up >= 10:
up = 1
cnt += 1
else:
up = 0
return cnt
결과
lines = []
while True: # multiline 입력받기
line = input()
if line != '0 0': lines.append(line)
else: break
for x in lines: # 출력하기
carrying = carry_over(x.split())
if carrying == 0:
print("No carry operation")
else:
print("%d carry operation" % carrying)
더해진 결과 자리수가 더해지는 두 수의 최댓값보다 작아지면 carry 가 일어난 거라는 원리로 풀었습니다.
풀고 나서 훑어보니 그렇게 푸신 분이 또 있네요.
자바스크립트는 undefined 처리를 열심히 해줘야 해서 좀 귀찮군요 ^^
javascript(ES6)
var countCarry = function(input) {
var inputs = input.split("\n").map(v => v.trim());
for (line of inputs) {
var [num1, num2] = line.split(" ").map(v => parseInt(v, 10));
var sum = num1 + num2;
if (sum === 0) return;
var arr1 = ("" + num1).split("").reverse();
var arr2 = ("" + num2).split("").reverse();
var carry = ("" + sum).split("").reverse();
var c = carry.map((v, i) => v < Math.max(arr1[i] || 0, arr2[i] || 0) ? 1 : 0).reduce((a, b) => a + b);
console.log(`${c ? c : "No"} carry operation${c > 1 ? "s" : ""}.`);
}
};
var input =
`123 456
555 555
123 594
9999999999 1
19999544 456
508 12
1 9999999999
678 322
0 0`;
countCarry(input);
#코딩도장 11번 문제
def result(up) :
if up != 0 :
print('{0} carry operartion'.format(up))
else :
print('No carry operation')
#뒤에서부터 한 숫자씩 계산을 하면서 10이 넘어가면 count += 1을 해줘
#올림연산을 했다는 것을 알려줍니다.
def proc() :
num1 = '525'; num2 = '55555'
count = 0; up = 0; i =0
while i < len(num1) and i < len(num2) :
temp = int(num1[len(num1)-i-1]) + int(num2[len(num2)-i-1]) + count
if temp >= 10 :
count += 1; up += 1
else :
count = 0
i += 1
return up
res = proc(); result(res)
[Python 3.6]
def countUpCalc(inStr):
lineData = inStr.strip().split("\n")
for line in lineData:
numArr = line.strip().split()
if numArr[0] == numArr[1] == '0': break
upCnt = addNum = 0
for i in range(10):
num1 = getNumber(numArr[0], i)
num2 = getNumber(numArr[1], i)
if num1 == num2 == 0: break
if num1 + num2 + addNum >= 10: upCnt += 1; addNum = 1
else: addNum = 0
if upCnt == 0: upCnt = "No"
print("{0} carry operation.".format(upCnt))
def getNumber(numStr, index):
numLen = len(numStr)
if numLen <= index or 0 > index: return 0
return int(numStr[index])
inStr="""
123 456
555 555
123 594
0 0
"""
countUpCalc(inStr)
#include<stdio.h>
#include<math.h>
int CarryCount(int num1, int num2);
int Length(int num);
int main(void)
{
int num1, num2, result;
while (1)
{
scanf("%d %d", &num1, &num2);
if (num1 == 0 && num2 == 0)
break;
result = CarryCount(num1, num2);
printf("Number of Carries : %d", result);
}
return 0;
}
int Length(int num)
{
int cnt = 0;
while (num * 10 / 10 != 0)
{
cnt += 1;
num = num / 10;
}
return cnt;
}
int CarryCount(int num1, int num2)
{
int cnt = 0;
int i;
int temp_cnt = 0;
int len_lim = Length(num1) >= Length(num2) ? Length(num2) : Length(num1);
for (i = 1; i <= len_lim; i++)
{
if (((num1 / ((int)pow(10, i-1))) % 10 + (num2 / ((int)pow(10, i-1))) % 10 + temp_cnt) / 10 != 0)
{
cnt += 1;
temp_cnt = 1;
}
else
temp_cnt = 0;
}
return cnt;
}
def carries(a, b):
cnt = c = 0
while a or b:
a, b, c = a // 10, b // 10, (a % 10 + b % 10 + c) // 10
cnt += c
return cnt
data = '123 456\n555 555\n123 594\n1234 999\n99999 111\n0 0'
for line in data.split('\n')[:-1]:
print(carries(int(line.split()[0]), int(line.split()[1])))
import java.util.Scanner;
public class Lv2 {
public int func(){
Scanner sc = new Scanner(System.in);
int carry = 0;
char[] op1 = String.valueOf(sc.nextInt()).toCharArray();
char[] op2 = String.valueOf(sc.nextInt()).toCharArray();
if ((op1.length == 1 && op2.length == 1)&& (op1[0] == '0'
&& op2[0] == '0')) return -1;
for(int i = 0; i < op1.length; i++)
if ((op1[i] - 48) + (op2[i] - 48) >= 10) carry++;
return carry;
}
public static void main(String[] args){
Lv2 obj = new Lv2();
while(true){
int i = obj.func();
if(i == -1) break;
else if (i == 0) System.out.println("No carry operation");
else System.out.println(i + " carry operation");
}
}
}
import java.util.Arrays;
import java.util.Scanner;
public class Example11 {
public static void main(String[] args) {
Example11 ex = new Example11();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("두 개의 숫자(정수)를 입력해 주세요 : ");
long num1 = sc.nextLong();
long num2 = sc.nextLong();
// 범위 체크
if ((long) (Math.log10(num1) + 1) > 9 || (long) (Math.log10(num2) + 1) > 9) {
System.out.println("범위가 넘어갔습니다.");
}
if (num1 == 0 && num2 == 0)
break;
ex.primaryArithmetic(num1, num2);
}
sc.close();
System.out.print("Bye Byte");
}
private void primaryArithmetic(long n1, long n2) {
String s1 = reverse(String.valueOf(n1));
String s2 = reverse(String.valueOf(n2));
int[] n1Array = Arrays.stream(s1.split("")).mapToInt(Integer::parseInt).toArray();
int[] n2Array = Arrays.stream(s2.split("")).mapToInt(Integer::parseInt).toArray();
int max = Math.max(n1Array.length, n2Array.length);
int carryCount = 0;
int increase = 0;
for (int i = 0; i < max; i++) {
int sum = 0;
if (i < n1Array.length)
sum += n1Array[i];
if (i < n2Array.length)
sum += n2Array[i];
sum += increase;
if (sum > 9) {
carryCount++;
increase = 1;
} else {
increase = 0;
}
}
System.out.println(carryCount + " carry operations.");
}
private String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
}
reverse 시킨다음 배열로 처리했는데 다른분들 보니까 %로 계산해서 훨씬 코드가 깔끔하네요. 두 number가 자리수가 다를때를 고려하다보니 코드가 복잡해 졌네요. 배우고 갑니다.
def f(num1, num2):
result = 0
while num1>=1 and num2>=1:
num1 = list(divmod(num1, 10))
num2 = list(divmod(num2, 10))
if (num1[1] + num2[1]) >= 10:
result += 1
num1[0] += 1
num1 = num1[0]
num2 = num2[0]
print((lambda x:'No' if result == 0 else str(result))(result), 'carry operation.')
f(123, 456)
f(555, 555)
f(123, 594)
a2 = []
b2 = []
a1 = str(input('first number: '))
b1 = str(input('second number: '))
a2 += a1
b2 += b1
a2.reverse()
b2.reverse()
if len(b2) <= len(a2):
N = len(a2)
for i in range(len(a2)-len(b2)):
b2.append('0')
elif len(b2) >= len(a2):
N = len(b2)
for i in range(len(b2)-len(a2)):
a2.append('0')
c = 0
for i in range(0, N):
A = int(a2[i])
B = int(b2[i])
if A + B >= 10:
c += 1
print("%s carry operation." %c)
Python3 입니다. 숫자가 3자리 수를 넘고, 두 수의 자릿수가 달라도 계산이 되도록 만들어는 봤는데;; 이렇게 하는게 맞는지 모르겠내요
변수 절약하기가 힘드네요..
#include <iostream>
using namespace std;
int carryCheck(int a, int b) {
int ans = 0;
do {
a % 10 + b % 10 >= 10 ? ans++ : 0;
a /= 10; b /= 10;
} while (a!=0 && b != 0);
return ans;
}
int main() {
int arr[2][100];
int ans=0, cnt=0;
for (int i = 0; i < sizeof(arr[0])/sizeof(int); i++) {
cin >> arr[0][i] >> arr[1][i];
if (arr[0][i] == 0 && arr[1][i] == 0) break;
cnt++;
}
for(int i=0;i<cnt;i++){
ans = carryCheck(arr[0][i], arr[1][i]);
if (ans == 0) cout << "No carry operation." << endl;
else if (ans == 1) cout << "1 carry operation." << endl;
else cout << ans << " carry operations." << endl;
}
return 0;
}
# python 3.6
import itertools as it
def carry(stra, strb):
# 숫자의 문자열을 우측부터 zip
lst = it.zip_longest(stra[::-1], strb[::-1], fillvalue="0")
lst = [(int(x), int(y)) for (x, y) in lst]
add = 0
carry = 0
for tup in lst:
add = (tup[0] + tup[1] + add) // 10 # 자리수 합 >= 10 --> 다음 자리 합에 반영
if add >= 1:
carry += 1
# 반환 문자열 설정
if carry < 2:
stmnt = "operation."
else:
stmnt = "operations."
if carry == 0:
carry = "No"
return "%s carry %s\n" % (carry, stmnt)
string = ""
while True:
get = input().split(" ")
chkL = get[0]
chkR = get[1]
if chkL == "0" and chkR == "0":
print(string)
break
string += carry(chkL, chkR)
# input:
# 123 456
# 1234 86
# 1234 766
# 0 0
# output:
# No carry operation.
# 2 carry operations.
# 3 carry operations.
inputOne = 1
inputTwo = 1
lists = []
count = 0
while inputOne != '0' and inputTwo != '0':
inputOne = input()
inputTwo = input()
if inputOne != '0' and inputTwo != '0':
lists.append((inputOne, inputTwo))
def calculate(first, last, count):
if int(first[len(first)-1]) + int(last[len(last)-1]) >= 10:
plus = int(first[len(first)-1]) + int(last[len(last)-1]) - 10
count = count + 1
first.pop()
last.pop()
if len(first) > 0:
first[len(first)-1] = int(first[len(first)-1]) + plus
return count
else:
first.pop()
last.pop()
return count
for (first,last) in lists:
first = list(first)
lenf = len(first)-1
last = list(last)
lenl = len(last)-1
for num in range(len(first)):
count = calculate(first, last, count)
if num == lenf:
print("%s carry operations" % "NO" if count == 0 else count)
package codingdojang;
public class ex11 {
public static void check(int x,int y) {
int count = 0;
while(x>=1 && y>=1) {
if(x%10 + y%10 >= 10) {
count++;
x = x%10 + y%10 + x/10;
y = y/10;
}
else {
x = x/10;
y = y/10;
}
}
System.out.println(count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 512;
int y = 589;
check(x,y);
}
}
# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3) on Mac
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')
# 첫 번째 계산
# 아이들은 여러 자리 숫자들을 더하기 위해서 우에서 좌로 숫자를 하나씩 차례대로 더 하라고 배웠다.
# 1을 한 숫자 위치에서 다음 자리로 더하기위해 이동하는 "한자리올림"연산을 많이 발견하는 것은 중요한 도전이 된다.
# 당신의 일은 교육자가 그들의 어려움을 평가하기 위하여, 덧셈 문제들의 각 집합에 대해서 한자리올림 연산들의 수를 계산하는 것이다.
# > 입력
# 입력의 각 라인은 10개의 숫자들보다 미만인 양의 정수들 두 개를 포함한다. 입력의 마지막 라인은 0 0 을 포한한다.
# > 출력
# 마지막을 제외한 입력의 각 라인에 대해서 당신은 두 숫자들을 더한 결과에서 한자리올림 연산들의 수를 아래 처럼 보여지는 형식으로 계산하여 출력해야 한다.
# > 입력 샘플
# 123 456
# 555 555
# 123 594
# 0 0
# > 출력 샘플
# No carry operation.
# 3 carry operations.
# 1 carry operation.
while True:
numbers = input("더할 두 수는 : ")
if numbers == '0 0':
break
n1, n2 = numbers.split()
n1_len = len(n1)
n2_len = len(n2)
if n1_len < n2_len:
n1 = '0' * (n2_len - n1_len) + n1
elif n1_len > n2_len:
n2 = '0' * (n1_len - n2_len) + n2
carry_num = sum([1 if int(n1[i]) + int(n2[i]) > 9 else 0 for i in range(len(n1))])
if carry_num:
print(carry_num, "carry operations.")
else:
print("None carry operation.")
int main()
{
int a;
int b;
int k;
int l;
int m=0;
int c=0;
scanf("%d %d", &a, &b);
while (a > 0 || b>0)
{
k = a % 10;
l = b % 10;
m=k+l+m/10;
if (m>=10)
c++;
a /= 10;
b /= 10;
}
printf("%d carry \n", c);
getchar();
return 0;
}
#include <iostream>
using namespace std;
int Pow(int num)
{
if (num <= 0)
return 1;
num--;
return (10 * Pow(num));
}
int CarryCounter(int num1, int num2)
{
int carryCount = 0;
int sum = 0;
int cnt = 1;
while (1)
{
int temp = sum;
sum = num1 % Pow(cnt) + num2 % Pow(cnt);
num1 -= num1%Pow(cnt);
num2 -= num2%Pow(cnt);
if (sum / Pow(cnt) > 0)
{
carryCount++;
num1 += Pow(cnt);
}
cnt++;
if (temp == sum)
break;
}
return carryCount;
}
void main()
{
int first, second;
cout << "첫번째 수 :";
cin >> first;
cout << "두번째 수 :";
cin >> second;
cout <<"합계 : "<<first+second <<", Carry : "<< CarryCounter(first, second) << endl;
system("pause");
}
단순 무식! VisualStudio2017 C++
def solution(x, y):
prev = 0
cnt = 0
while x >=1 and y >= 1:
if (x % 10) + (y % 10) + prev >= 10:
prev = 1
cnt += 1
else:
prev = 0
x = x // 10
y = y // 10
print(cnt)
# input 받기
while True:
inp = str(input())
inp = inp.split()
x = inp[0]
y = inp[1]
if int(x) != 0 and int(y) != 0:
solution(int(x), int(y))
else:
break
def carry(tup):
x=tup[0]
y=tup[1]
result=0
for i in range(min(len(x), len(y))):
if eval(x[-i]+'+'+y[-i])>9:
result+=1
return(result)
samp=[0]
while samp[-1]!=('0', '0'):
nums=list(map(str, input('두 양의 정수(끝내려면 0 0): ').split()))
if len(nums)==2:
samp.append(tuple(nums))
else:
samp=samp[1:-1]
for i in samp:
print(carry(i))
up_val=0
result_list = []
while True:
vv = []
k = input("10자리 미만 숫자 두그룹 입력하세요 :")
if k == "0 0":
break
resize_k1, resize_k2 = k.split(" ")
if len(str(resize_k1)) != len(str(resize_k2)):
max_len = max(len(str(resize_k1)), len(str(resize_k2)))
resize_k1 = "{0:0>{1}}".format(str(resize_k1), max_len)
resize_k2 = "{0:0>{1}}".format(str(resize_k2), max_len)
for x in range(len(str(resize_k1))-1,-1,-1):
sum_k = int(str(resize_k1)[x:]) + int(str(resize_k2)[x:])
if len(str(sum_k)) > len(str(resize_k1)[x:]):
vv.append(1)
result_list.append(len(vv))
for x in result_list:
print("{0} carry operation.".format(x))
def primary_arithmetic(num1,num2): result_num = 0 box = 'carry operations.'
for i in range(len(str(num1))):
if int(str(num1)[i]) + int(str(num2)[i]) > 9:
result_num += 1
else : result_num += 0
if result_num == 0:
return 'No carry operation.'
result_box = '{} carry opreations.'.format(result_num)
return result_box
print(primary_arithmetic(123, 456)) print(primary_arithmetic(555, 555)) print(primary_arithmetic(123, 594)) print(primary_arithmetic(0, 0))```{.python} def primary_arithmetic(num1,num2): result_num = 0 box = 'carry operations.'
for i in range(len(str(num1))):
if int(str(num1)[i]) + int(str(num2)[i]) > 9:
result_num += 1
else : result_num += 0
if result_num == 0:
return 'No carry operation.'
result_box = '{} carry opreations.'.format(result_num)
return result_box
print(primary_arithmetic(123, 456)) print(primary_arithmetic(555, 555)) print(primary_arithmetic(123, 594)) print(primary_arithmetic(0, 0)) ```
파이썬 3.6
# 수의 쌍을 입력받을 리스트 객체 정의
pairlist = []
# 수의 쌍을 리스트로 입력 받아 다시 리스트에 저장
def numinput():
numpair = []
a = input(" 1) 쌍의 첫번째 수를 입력하세요 :")
if len(a) > 9:
print(" ※ 10자리 미만인 수를 입력해주세요.")
return
b = input(" 2) 쌍의 두번째 수를 입력하세요 :")
if len(b) > 9:
print(" ※ 10자리 미만인 수를 입력해주세요.")
return
numpair.append(a)
numpair.append(b)
# 입력받은 수의 쌍이 0 , 0 이면 입력을 멈추고 올림연산 계산
if a == '0' and b == '0':
pairlist.append(numpair)
print("\n","==input==","\n")
for i in pairlist:
print( " %s %s " %(i[0],i[1]),"\n")
main(pairlist)
else:
pairlist.append(numpair)
numinput()
def main(x):
count = 0
roundup = 0
print(" ==output==","\n")
for i in pairlist:
# 입력받은 수의 쌍이 0, 0이면 올임연산에서 제외
if i[0] == '0' and i[1] == '0':
pass
else:
# 각 수의 쌍을 우에서 좌로 더하여 올림연산 횟수 카운트
reversepair = list(zip(list(i[0]),list(i[1])))
reversepair.reverse()
for i in reversepair:
if roundup == 1:
if int(i[0])+int(i[1]) + roundup >= 10:
count +=1
else:
roundup -= 1
if roundup == 0:
if int(i[0])+int(i[1]) >= 10:
count += 1
roundup +=1
if count == 0:
print(" No carry operation.","\n")
elif count > 1:
print(" %d carry operations." % count,"\n")
count = 0
else:
print(" %d carry operation." % count,"\n")
count = 0
numinput()
*결과값
1) 쌍의 첫번째 수를 입력하세요 :123
2) 쌍의 두번째 수를 입력하세요 :456
1) 쌍의 첫번째 수를 입력하세요 :555
2) 쌍의 두번째 수를 입력하세요 :555
1) 쌍의 첫번째 수를 입력하세요 :123
2) 쌍의 두번째 수를 입력하세요 :594
1) 쌍의 첫번째 수를 입력하세요 :0
2) 쌍의 두번째 수를 입력하세요 :0
==input==
123 456
555 555
123 594
0 0
==output==
No carry operation.
3 carry operations.
1 carry operation.
파이썬
def cal(A, B, alpha = 0):
ans = 0
O = max(len(A), len(B))
A = "0" * (O - len(A)) + A
B = "0" * (O - len(B)) + B
if int(A) == int(B) == 0:
return
for i in range(O)[::-1]:
if int(A[i]) + int(B[i]) + alpha >= 10:
ans += 1
alpha = 1
else:
alpha = 0
if ans == "0": ans = "No"
print("%s carry operation" % ans)
a = b = ""
while True:
number1 = input("number1 : ")
number2 = input("number2 : ")
if len(number1) >= 10 or len(number2) >= 10:
print("too much")
continue
if int(number1) == int(number2) == 0:
a += "0"
b += "0"
break
a += number1 + " "
b += number2 + " "
A = a.split(" ")
B = b.split(" ")
for i in range(len(A)): cal(A[i], B[i])
package primaryArithmetic;
public class PrimaryArithmetic {
public int primaryArithmetic(int n, int m) {
int result = 0;
int[] nArray = Integer.toString(n).chars().map(ele -> Character.getNumericValue(ele)).toArray();
int[] mArray = Integer.toString(m).chars().map(ele -> Character.getNumericValue(ele)).toArray();
if (nArray.length != mArray.length)
System.out.println("not same length to two number");
int length = (nArray.length > mArray.length) ? nArray.length : mArray.length;
int upper = 0;
for (int i = 1; i <= length; i++) {
if (nArray.length - i >= 0 && mArray.length - i >= 0) {
if (nArray[nArray.length - i] + mArray[mArray.length - i] + upper >= 10) {
result++;
upper++;
} else
upper = 0;
} else if (upper == 0)
break;
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PrimaryArithmetic pa = new PrimaryArithmetic();
System.out.println(pa.primaryArithmetic(123, 456) + " carry operation.");
System.out.println(pa.primaryArithmetic(555, 555) + " carry operation.");
System.out.println(pa.primaryArithmetic(123, 594) + " carry operation.");
System.out.println(pa.primaryArithmetic(12345, 12) + " carry operation.");
System.out.println(pa.primaryArithmetic(12345, 15) + " carry operation.");
System.out.println(pa.primaryArithmetic(12345, 15) + " carry operation.");
System.out.println(pa.primaryArithmetic(12345, 55) + " carry operation.");
System.out.println();
System.out.println(pa.primaryArithmetic2(123, 456) + " carry operation.");
System.out.println(pa.primaryArithmetic2(555, 555) + " carry operation.");
System.out.println(pa.primaryArithmetic2(123, 594) + " carry operation.");
System.out.println(pa.primaryArithmetic2(12345, 12) + " carry operation.");
System.out.println(pa.primaryArithmetic2(12345, 15) + " carry operation.");
System.out.println(pa.primaryArithmetic2(12345, 15) + " carry operation.");
System.out.println(pa.primaryArithmetic2(12345, 55) + " carry operation.");
}
private int primaryArithmetic2(int x, int y) {
int count = 0;
int upper = 0;
while (x >= 1 && y >= 1) {
if ((x % 10 + y % 10 + upper) >= 10) {
count++;
upper++;
} else
upper = 0;
x = x / 10;
y = y / 10;
}
return count;
}
}
function _array_setting (a, b) {
var _a_string = String(a);
var _b_string = String(b);
var _a_length = _a_string.length;
var _b_length = _b_string.length;
var _length = 0;
if (_a_length > _b_length) {
_length = _b_length;
} else {
_length = _a_length;
}
var _array_a = new Array;
var _array_b = new Array;
for (var i = 0; i < _length; i++) {
_array_a[i] = parseInt(_a_string[_a_length - i - 1]);
_array_b[i] = parseInt(_b_string[_b_length - i - 1]);
}
return [_array_a, _array_b];
};
function _sum_up (x) {
var _length_up = x[0].length;
var _upper = 0;
var _count = 0;
for (var i = 0; i < _length_up; i++) {
if (x[0][i] + x[1][i] + _upper >= 10) {
_upper = 1;
_count = _count + 1;
} else {
_upper = 0;
}
}
return _count;
};
function _conclusion (a, b) {
return _sum_up(_array_setting(a,b));
};
console.log(_conclusion(123,594));
무언가 만들긴 했는데 괴랄하고 제대로 못 만든거 같네요;;
# 파이썬
input_list = []
while 1:
input1 = input("blank between two numbers: ")
if input1 == "0 0": break
input_list.append(input1)
for m in input_list:
u, v = m[::-1].split()
carry = 0
for n in range(min([len(u), len(v)])):
if int(u[n]) + int(v[n]) >= 10:
carry += 1
print(carry, "carry operations")
def primary(m,n):
def numbersum(l):
if l >= 10:
return numbersum(l//10)+ l % 10
else: return l
c = int((-numbersum(m+n)+numbersum(m)+numbersum(n))/9)
if c == 0:
c = 'No'
return c
while 1:
a = input("덧셈할 두 수를 입력하시오(공백으로 구분) :").strip()
if a == '0 0':
break
b = tuple(map(int,a.split(' ')))
print("{0} carry operations".format(primary(b[0], b[1])))
파이썬으로 작성했습니다
mylist=[]
while True:
y=input('').split(' ')
if y[0] and y[1] == '0':
break
mylist.append([int(x) for x in y])
for x in mylist:
count=0
one, two=list(str(x[0])), list(str(x[1]))
for y in range(1, min(len(one),len(two))+1):
if int(one[-1*y])+int(two[-1*y])>9:
count+=1
if count==0:
print('No carry operation')
else:
print('%d carry operation' %count)
자릿수 다를경우도 고려함
line_num=int(input("입력할 라인의 개수를 입력하세요\n")) #마지막 00포함한라인 포함
line_x=[]
line_y=[]
for k in range(line_num):
line_x.append(input("왼쪽숫자를 입력하세요\n"))
line_y.append(input("오른쪽숫자를 입력하세요\n"))
counter_list=[]
for g in range(line_num-1):
temp_counter=0
for b in range(max(len(line_x),len(line_y))):
if (int(line_x[g][-(b+1):])+int(line_y[g][-(b+1):]))>=10**(b+1):
temp_counter+=1
if temp_counter==0:
counter_list.append("No")
else:
counter_list.append(temp_counter)
for a in range(line_num-1):
print("%s carry operation."%counter_list[a])
public class CarryOperation {
String str1;
String str2;
Stack<Integer> st1 = new Stack<Integer>();
Stack<Integer> st2 = new Stack<Integer>();
public CarryOperation(String str) {
String[] twoStr = str.split(" ");
this.str1 = twoStr[0];
this.str2 = twoStr[1];
}
public boolean digitPush() {
for(int i = 0; i < str1.length(); i++) {
st1.push(Integer.parseInt(str1.charAt(i)+""));
}
for(int i = 0; i < str2.length(); i++) {
st2.push(Integer.parseInt(str2.charAt(i)+""));
}
return true;
}
public void digitDisplay() {
System.out.print(str1 + "," + str2 + ": ");
}
public int digitPop() {
int number1, number2;
int sum = 0;
int toAddNumber = 0;
while(st1.size() > 0 && st2.size() > 0) {
number1 = st1.pop();
number2 = st2.pop();
if((number1 + number2 + toAddNumber) >= 10) {
sum++;
toAddNumber = 1;
} else {
toAddNumber = 0;
}
}
return sum;
}
public static void main(String[] args) {
System.out.println("더하기 할 숫자 두개를 입력하세요: ");
Scanner sc = new Scanner(System.in);
String[] twoStr;
List<String> strArrayList = new ArrayList<String>();
int number1, number2;
CarryOperation co;
do {
String str = sc.nextLine();
twoStr = str.split(" ");
number1 = Integer.parseInt(twoStr[0]);
number2 = Integer.parseInt(twoStr[1]);
if((number1 != 0) && (number2 != 0)) {
strArrayList.add(str);
}
} while((number1 != 0) && (number2 != 0));
for(String str : strArrayList) {
co = new CarryOperation(str);
co.digitPush();
co.digitDisplay();
System.out.println(co.digitPop() + " carry operation.");
}
sc.close();
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PrimaryArithmetic {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<>();
while(sc.hasNext()){
String inputLine = sc.nextLine();
if(inputLine.equals("0 0")){
break;
}else{
list.add(inputLine);
}
}
sc.close();
for(int i=0; i< list.size(); i++){
String[] values = list.get(i).split(" ");
int left = Integer.parseInt(values[0]);
int right = Integer.parseInt(values[1]);
int count = 0;
while(left > 0 && right > 0){
int l_digit = left % 10;
left /= 10;
int r_digit = right % 10;
right /= 10;
if(l_digit+ r_digit > 9){
count++;
left++;
}
}
System.out.println( (count == 0 ? "No" : count) + " carry operations.");
}
}
}
123 456
555 555
123 594
0 0
No carry operations.
3 carry operations.
1 carry operations.
/* Primary Arithmetic */
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func main() {
var (
inp1, inp2 int
msg string
)
for {
fmt.Scanf("%d %d\n", &inp1, &inp2)
if inp1 == 0 && inp2 == 0 {
fmt.Println(msg)
os.Exit(0)
}
msg += (countCarry(inp1, inp2) + "\n")
}
}
func num2array(num int) [10]int {
var rst [10]int
for idx, val := range strings.Split(fmt.Sprintf("%10d", num), "") {
rst[idx], _ = strconv.Atoi(val)
}
return rst
}
func countCarry(n1, n2 int) string {
num1, num2 := num2array(n1), num2array(n2)
count, carry := 0, 0
for idx := len(num1) - 1; idx > 0; idx-- {
if num1[idx]+num2[idx]+carry >= 10 {
carry = 1
count++
} else {
carry = 0
}
}
var msg string
if count > 0 {
msg = strconv.Itoa(count) + " carry operations."
} else {
msg = "No carry operations."
}
return msg
}
d:/sample.txt 에 내용이
123 456 555 555 123 789 123 594 3642 358 89834 89 0 0 일때
def prim(filename) :
fp = open('D:/{}'.format(filename),'r')
while True :
data = fp.readline().strip()
if data == "0 0": break
data_list= data.split(" ")
data_list[0] = '0' * len(data_list[1]) + data_list[0]
data_list[1] = '0' * len(data_list[0]) + data_list[1]
carry = 0
cflag = 0
for i,j in zip(data_list[0][::-1],data_list[1][::-1]) :
if int(i) + int(j) + cflag > 9 :
carry += 1
cflag =1
else : cflag = 0
if carry == 0 : print("{} ==> No carry operation.".format(data))
else : print("{0} ==> {1} carry operations".format(data,carry))
fp.close()
prim('sample.txt')
Swift입니다.
import Foundation
func getCarryCount(_ n1: Int, _ n2: Int) -> Int {
let n1Array = Array(String(n1).reversed())
let n2Array = Array(String(n2).reversed())
let count = max(n1Array.count, n2Array.count)
var carryCount = 0
var carryOver = 0
for i in 0..<count {
let n1Digit = i < n1Array.count ? Int(String(n1Array[i]))! : 0
let n2Digit = i < n2Array.count ? Int(String(n2Array[i]))! : 0
if n1Digit + n2Digit + carryOver >= 10 {
carryOver = 1
carryCount += 1
} else {
carryOver = 0
}
}
return carryCount
}
print("123 + 456 = \(123 + 456) : Carry operation \(getCarryCount(123, 456))")
print("555 + 555 = \(555 + 555) : Carry operation \(getCarryCount(555, 555))")
print("123 + 594 = \(123 + 594) : Carry operation \(getCarryCount(123, 594))")
print("1 + 99999 = \(1 + 99999) : Carry operation \(getCarryCount( 1, 99999))")
실행 결과는...
123 + 456 = 579 : Carry operation 0
555 + 555 = 1110 : Carry operation 3
123 + 594 = 717 : Carry operation 1
1 + 99999 = 100000 : Carry operation 5
while True:
a, b = input().split()
if (a == '0' and b == '0'):
break
a2 = str(a)
b2 = str(b)
a1 = len(str(a))
b1 = len(str(b))
k = min(a1, b1)
count = 0
h = 0
for i in range(k):
if h == 1:
if int(a2[a1 - i - 1]) + int(b2[b1 - i - 1]) + 1 > 9:
h = 1
count = count + 1
else:
if int(a2[a1 - i - 1]) + int(b2[b1 - i - 1]) > 9:
h = 1
count = count + 1
if count == 0:
print('No carry operation.')
else:
print(str(count) + ' carry operation.')
자리수 무관하게 해결해주는 함수입니다. (댓글에 어떤분이 1 99999 같은 경우도 가능하게 해달라 하셔서..)
def pri_arith():
def in_put(): # 입력값을 받아 리스트를 생성
num = [] # [[123, 456], [111, 99], [456, 123]] 과 같이 입력받는 리스트
j = 0
while True: # '0 0'을 받을때까지 입력 무한 반복
j += 1
a, b = input('please enter %dth numbers : ' % j).split()
num.append([a, b])
if int(a) == int(b) == 0: # '0 0' 을 입력하면 입력 종료
break
return num
data = in_put() # 입력값
result = [] # 결과값이 저장될 리스트
for x in data:
m = max(len(x[0]), len(x[1]))
carry = 0 # 한자리올림의 수
temp = [0] # 자리값 올림할 공간 생성
while len(x[0]) < m: # 입력값 두개의 길이를 맞춰줌 ex) [12, 34567] -> [00012, 34567]
x[0] = '0' + x[0]
while len(x[1]) < m:
x[1] = '0' + x[1]
x0, x1 = list(x[0]), list(x[1]) # x0, x1 는 길이 m인 리스트
while len(x0) > 0:
if int(x0.pop()) + int(x1.pop()) + temp.pop() >= 10: # 1의자리 합( pop : 뒤에서 원소가 하나씩 빠짐)
carry += 1 # 한자리올림의 수 + 1
temp.append(1) # 자리값올림해서 10의 자리에 더할 1 생성
else: # 합이 10 미만이면
temp.append(0) # 자리값올림이 없으므로 0
result.append(carry) # 결과값 리스트에 결과값을 넣음
for i in range(len(result) - 1): # 결과값을 출력 ( -1 해주는건 0 0 의 결과값 제거)
print('%dth : No carry operation.' % (i+1) if result[i] == 0 else
'%dth : %d carry operation.' % (i+1, result[i]))
try:
pri_arith()
except ValueError as v:
print('Wrong input data.', v)
please enter 1th numbers : 1 99999
please enter 2th numbers : 456 789
please enter 3th numbers : 0 99
please enter 4th numbers : 12 88
please enter 5th numbers : 0 0
1th : 5 carry operation.
2th : 3 carry operation.
3th : No carry operation.
4th : 2 carry operation.
Process finished with exit code 0
import java.util.Scanner;
public class 2 {
public static void main(String[] args) {
Scanner num=new Scanner(System.in);
int in1, in2, r1, r2, temp=0, result=0;
in1=num.nextInt(); in2=num.nextInt(); //값을 입력받음
for(int m=1; in1/m!=0 || in2/m!=0 ; m*=10){
r1=(in1/m)%10; r2=(in2/m)%10;
if((r1+r2+temp)>=10){ result++; temp=1; }
else temp=0;
}//요기부터 출력
if(result>0) System.out.print(result);
else System.out.print("No");
System.out.print(" carry operation");
if(result>1) System.out.print("s");
System.out.print(".");
}
}
Python 3
def PrimaryArithmetic(st, nd):
times = [0]
each = list(zip([int(x) for x in str(st)], [int(y) for y in str(nd)]))
for contrast in each:
times.append((sum(contrast) + times[-1])//10)
return sum(times)
sumthing = []
while True:
ans = input()
if ans == '0 0': break
else: sumthing.append(ans.split())
for add in sumthing:
if PrimaryArithmetic(int(add[0]), int(add[1])) == 1: print(str(PrimaryArithmetic(int(add[0]), int(add[1]))) + ' carry operation.')
elif PrimaryArithmetic(int(add[0]), int(add[1])): print(str(PrimaryArithmetic(int(add[0]), int(add[1]))) + ' carry operations.')
else: print('No carry operation.')
PrimaryArithmetic함수가 두 수 사이의 받아올림 횟수를 구하고, while문에서 입력을 받아 for문에서 출력하는 방식입니다
// 자바입니다
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String[] str = br.readLine().split(" ");
if (str[0].equals("0")) break; // 0 을 입력 받으면 끝냄
if(str[0].length() > str[1].length()) { // 같은 자리수가 아닐 때 앞에 0을 붙여줌, 포문 아웃인덱스 안 뜨게하려고
String tmp = new StringBuffer(str[1]).reverse().toString();
while(tmp.length() != str[0].length())
tmp += "0";
str[1] = new StringBuffer(tmp).reverse().toString();
} else if (str[0].length() < str[1].length()) {
String tmp = new StringBuffer(str[2]).reverse().toString();
while(tmp.length() != str[1].length())
tmp += "0";
str[2] = new StringBuffer(tmp).reverse().toString();
}
int cnt = 0; // 올림 계산 카운트
int up = 0; // 올림 계산
for (int i=str[0].length()-1; i>=0; i--) {
int a = Integer.parseInt(str[0].charAt(i) + "") + up;
int b = Integer.parseInt(str[1].charAt(i) + "");
if (a+b >= 10) {
cnt++;
up = 1; //올림이 발생하면 1로
} else
up = 0; //발생 안하면 0으로
}
System.out.println(cnt + " carry operation");
}
}
public class PrimaryArithmetic {
public static void main(String[] args) {
int a,b;
int carry=0;
Scanner scan=new Scanner(System.in);
System.out.print("A:");
a=scan.nextInt();
System.out.print("B:");
b=scan.nextInt();
while(a>=1&&b>=1) {
if((a%10+b%10)>=10) {
carry++;
}
a/=10;
b/=10;
}
if(carry>0) {
System.out.print(carry+" carry operation");
}else {
System.out.print("no carry operation" );
}
}
}
package h12_primary_arithmatic;
import java.util.Scanner;
public class PrimaryArithmatic {
public static void main(String[] args) {
Scanner num=new Scanner(System.in);
int in1, in2, r1, r2, temp=0, result=0;
in1=num.nextInt(); in2=num.nextInt(); //값을 입력받음
for(int m=1; in1/m!=0 || in2/m!=0 ; m*=10){
r1=(in1/m)%10; r2=(in2/m)%10;
if((r1+r2+temp)>=10){ result++; temp=1; }
else temp=0;
}//요기부터 출력
if(result>0) System.out.print(result);
else System.out.print("No");
System.out.print(" carry operation");
if(result>1) System.out.print("s");
System.out.print(".");
}
}
import java.util.Scanner;
public class PrimaryArithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num[] = new int[100];
int a = 0;
while (true) {
num[a++] = sc.nextInt();
if (num[a] == 0 && num[a - 1] == 0)
break;
}
for (int i = 0; i < num.length; i += 2) {
int count = 0;
if (num[i] != 0 && num[i + 1] != 0) {
for (int j = 0; j < 3; j++) {
if (num[i] % 10 + num[i + 1] % 10 > 9) {
count++;
}
num[i] /= 10;
num[i + 1] /= 10;
}
System.out.println((count == 0 ? "No" : count) + " carry operation.");
}
}
}
}
def arithmetic(n1, n2):
carry = 0
puton = 0
for i in range(min(len(str(n1)), len(str(n2)))):
if (int(n1[-i+1]) + int(n2[-i+1]) + puton) >= 10:
carry += 1
if (int(n1[-i+1]) + int(n2[-i+1]) + puton) == 10:
puton = 1
else:
puton = 0
return carry
inp = input();
num1, num2 = inp.split()
print("carry = " + str(arithmetic(num1, num2)))
Python 길이가 좀 기네요..
while True:
x, y = input().split(' ')
if x == "0" and y == "0":
break
if int(y) > int(x):
x, y = y, x
x = x[::-1]; y = y[::-1];
if len(x) > len(y):
y += "0"*(len(x)-len(y))
ans = 0
prev = 0
for l in range(len(x)):
if int(x[l]) + int(y[l]) + prev > 9:
ans += 1
prev = 1
else:
prev = 0
if ans == 0:
print("No carry operation.")
elif ans == 1:
print("{} carry operation.".format(ans))
else:
print("{} carry operations.".format(ans))
#include <stdio.h>
int main() {
int n1, n2, carry=0, carryCnt=0;
int carryData[10], numOfData=0;
// 0 0 입력 전까지 반복.
while(1){
scanf("%d %d",&n1,&n2);
if(n1==0 && n2==0) break;
// 모든 자릿수를 더할때 까지 반복.
while(1) {
// 두 수의 합이 9보다 클 경우 carry = 1 유지
// 작을 경우 carry = 0 초기화
if(((n1%10+n2%10)+carry>9)) carry=1;
else carry=0;
// carry가 발생하면 카운트를 올리고
// 다음 자릿수를 설정한다. 두 수의 연산이 끝났다면 종료.
if(carry==1) carryCnt++;
n1/=10, n2/=10;
if(n1==0 && n2==0) break;
}
carryData[numOfData++]=carryCnt;
carryCnt=carry=0;
}
for(int i=0; i<numOfData; i++){
if(carryData[i]==0) printf("No carry operation\n");
else if(carryData[i]==1) printf("1 carry operation\n");
else printf("%d carry operations\n",carryData[i]);
}
}
자릿수가 달라도 테스팅 되도록 해보았습니다. 파이썬 입니다.
a, b = 1,1
while(a != 0 and b != 0):
a, b = (input("두 숫자를 입력해주세요(띄어쓰기로 구분): ").split())
if not (len(a) == len(b)):
length = len(a) if len(a) > len(b) else len(b)
c = length - len(a)
d = length - len(b)
a = '0' * c + a
b = '0' * d + b
carry = 0
temp = 0
for c, d in zip(a[::-1], b[::-1]):
if 10 <= int(c) + int(d) + temp:
carry += 1
temp = 1
else :
temp = 0
#print('temp:', temp)
if carry == 0:
print('No carry operation.')
else : print(carry, 'carry operation.')
'''output
두 숫자를 입력해주세요(띄어쓰기로 구분): 123 456
No carry operation.
두 숫자를 입력해주세요(띄어쓰기로 구분): 555 555
3 carry operation.
두 숫자를 입력해주세요(띄어쓰기로 구분): 123 594
1 carry operation.
두 숫자를 입력해주세요(띄어쓰기로 구분): 1 9999
4 carry operation.
두 숫자를 입력해주세요(띄어쓰기로 구분): 0 0
'''
import java.util.*;
public class Practice100 {
public static void main(String[] args) {
int carry_out=0, carry=0, small_size, large_size, sum;
while(true) {
int k=0;
System.out.println("숫자를 입력하라.\n첫번째:");
Scanner sc=new Scanner(System.in);
char[] chek_zero=sc.nextLine().toCharArray();
System.out.println("두번째:");
char[] chek_zero1=sc.nextLine().toCharArray();
int[] int1s=new int[chek_zero.length];
int[] int2s=new int[chek_zero1.length];
for(int i=0;i<chek_zero.length;i++) {
int1s[i]=chek_zero[i]-'0';
}
for(int i=0;i<chek_zero1.length;i++) {
int2s[i]=chek_zero1[i]-'0';
}
if(chek_zero[0]=='0'&&chek_zero1[0]=='0') {
System.out.println("종료.");
break;
}
carry=0;
for(int i=0;i<int1s.length/2;i++) {
int temp=int1s[i];
int1s[i]=int1s[int1s.length-1-i];
int1s[int1s.length-1-i]=temp;
}
for(int i=0;i<int2s.length/2;i++) {
int temp=int2s[i];
int2s[i]=int2s[int2s.length-1-i];
int2s[int2s.length-1-i]=temp;
}
if(int1s.length>=int2s.length) {
small_size=int2s.length;
large_size=int1s.length;
}else {
small_size=int1s.length;
large_size=int2s.length;
}
for(;k<small_size;k++) {
sum=int1s[k]+int2s[k]+carry_out;
if(sum>=10) {
carry_out=1;
carry++;
}else {
carry_out=0;
}
}
for(;k<large_size;k++) {
if(large_size==int1s.length) {
sum=int1s[k]+carry_out;
if(sum>=10) {
carry_out=1;
carry++;
}else {
carry_out=0;
}
}else {
sum=int2s[k]+carry_out;
if(sum>=10) {
carry_out=1;
carry++;
}else {
carry_out=0;
}
}
}
System.out.println(carry+"번의 캐리가 발생했습니다.");
}
}
}
def carry(n1,n2):
carry, count = 0, 0
if n1 > n2: n1, n2 = n2, n1
for i in range(len(str(n2))):
if i < len(str(n1)):
if (int(str(n1)[-(i+1)])+int(str(n2)[-(i+1)])+count)//10 == 1:
carry += 1
count = 1
else: count = 0
else:
if (int(str(n2)[-(i+1)])+count)//10 == 1:
carry += 1
count = 1
else: count = 0
if carry == 0: carry = 'No'
print('{} carry operation.'.format(carry))
m = []
while 1:
m.append(tuple(map(int, input().split())))
if m[-1] == (0, 0):
del m[-1]
break
for i in m: carry(i[0],i[1])
123 456
555 555
123 594
1 99999
0 0
No carry operation.
3 carry operation.
1 carry operation.
5 carry operation.
using System;
using System.Linq;
namespace CD011
{
class Program
{
static void Main(string[] args)
{
string resultMsg = String.Empty;
// 각 라인 입력 받아 올림 연산 메세지 출력
while (true)
{
var input = Console.ReadLine().Split();
if (input[0] == "0" && input[1] == "0") { break; }
var newCarryOperation = new Carry(int.Parse(input[0]), int.Parse(input[1]));
resultMsg += newCarryOperation.CarryMessage + Environment.NewLine;
}
Console.WriteLine(resultMsg);
}
}
class Carry
{
readonly int[] NumA, NumB;
public string CarryMessage // 올림 연산 수 표시 문자열
{
get
{
int result = NumCarry(NumA, NumB);
string pre = (result == 0) ? "No" : result.ToString();
string post = (result > 1) ? "s." : ".";
return pre + " carry operation" + post;
}
}
public Carry(int numA, int numB)
{
// int to array & sync array length
NumA = numA.ToString().Select(c => (int)Char.GetNumericValue(c)).ToArray();
NumB = numB.ToString().Select(c => (int)Char.GetNumericValue(c)).ToArray();
int size = Math.Max(numA, numB).ToString().Length;
Array.Reverse(NumA); Array.Reverse(NumB);
Array.Resize(ref NumA, size); Array.Resize(ref NumB, size);
}
// 올림 연산의 수 계산
static int NumCarry(int[] Arr1, int[] Arr2)
{
int numCarry = 0, overCarry = 0;
for (int idx = 0; idx < Arr1.Length; idx++)
{
int tmpVal = Arr1[idx] + Arr2[idx] + overCarry;
if (tmpVal >= 10)
{
overCarry = (int)(tmpVal /10);
numCarry++;
}
}
return numCarry;
}
}
}
123 456
555 555
123 594
1 99999
0 0
No carry operation.
3 carry operations.
1 carry operation.
5 carry operations.
#include<stdio.h>
#define MAX 10
int main(){
int front[MAX]={1,};
int end[MAX]={1,};
int positionalf[3];
int positionale[3];
int carrysum=0;
int hund[2],ten[2],one[2];
int i=0;//MAX is enough big
//input start
while(front[i]!=0&&end[i]!=0){
scanf("%d %d",front[i],end[i]);
i++;
}
//input end
i=0;
while(front[i]!=0&&end[i]!=0){
hund[0] = front[i]/100;
hund[1] = end[i]/100;
ten[0] = (front[i]-hund[0])/10;
ten[1] = (end[i]-hund[1])/10;
one[0] = front[i]-hund[0]-ten[0];
one[1] = end[i]-hund[1]-ten[1];
if(hund[0]+hund[1]>10){
carrysum++;
}
if(ten[0]+ten[1]>10){
carrysum++;
}
if(one[0]+one[1]>10){
carrysum++;
}
if(carrysum==0){
printf("No carry operation.");
}
else{
printf("%d carry operations.",carrysum);
}
}
}
// Primary Arithmetic
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> arr_1= new ArrayList<>();
ArrayList<Integer> arr_2= new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) // 정수입력받기
{
System.out.println("양의 정수 2개 입력: ");
int a = sc.nextInt();
int b = sc.nextInt();
if(a == 0 && b == 0) // 0 두개 입력받았을 때 종료
break;
else
{
arr_1.add(a);
arr_2.add(b);
}
}
for(int i = 0; i < arr_1.size(); i++)
{
long a = arr_1.get(i);
long b = arr_2.get(i);
getCarry(a, b);
}
}
public static void getCarry(long a, long b) // 캐리개수 계산
{
int carry = 0;
int carryCnt = 0;
int length_a = (int)(Math.log10(a) + 1); // a의 길이
int length_b = (int)(Math.log10(b) + 1); // b의 길이
int length_big = (length_a >= length_b ? length_a : length_b); // 더 큰 길이를 저장
while(length_big != 0)
{
int a_1 = (int)(a % 10); // a의 1의자릿수
int b_1 = (int)(b % 10); // b의 1의자릿수
a = (int)(a / 10); // 자리수를 낮춤
b = (int)(b / 10);
length_big--;
if(a_1 + b_1 + carry > 9)
{
carry = 1;
carryCnt++;
}
else
{
carry = 0;
}
}
if(carryCnt == 0)
System.out.println("No carry operation");
else
System.out.printf("%d carry operations\n", carryCnt);
}
}
while(length_big != 0) 의 의미는 예를들어 999 + 1 을 하면 최대 3개의 캐리가 생기므로 둘중 더 큰 길이만큼 반복한다는 뜻입니다.
l = []
while 1:
a,b = input().split()
if (a,b) == ('0','0'):
break
l.append( (a,b) )
for n in l:
carry_count = 0
(a,b) = (n[0], n[1])
a = a[::-1]
b = b[::-1]
if len(a) > len(b):
b = b + '0' * (len(a) - len(b))
else:
a = a + '0' * (len(b) - len(a))
carry = 0
for i in range(len(a)):
if (int(a[i]) + int(b[i]) + carry) >= 10:
carry_count += 1
carry = 1
print("{} carry operation".format(carry_count))
class Program
{
static void Main(string[] args)
{
int[] nArray = new int[10];
int nLoop = 0;
while (true)
{
string strCalc1, strCalc2;
string[] strArray = Console.ReadLine().Split(' ');
int nCnt = 0;
int nFst = int.Parse(strArray[0]);
int nSec = int.Parse(strArray[1]);
int nLength = strArray[0].Length;
if (nFst == 0 && nSec == 0)
{
for (int i = 0; i < nLoop; i++)
{
string strValue = (nArray[i] == 0) ? "No carry operation." : nArray[i] + " carry operations.";
Console.WriteLine(string.Format("{0}", strValue));
}
break;
}
for (int i = 0; i < nLength; i++)
{
char[] digits1 = strArray[0].ToCharArray();
char[] digits2 = strArray[1].ToCharArray();
strCalc1 = digits1[i].ToString();
strCalc2 = digits2[i].ToString();
if (int.Parse(strCalc1) + int.Parse(strCalc2) >= 10)
{
nCnt++;
}
}
nArray[nLoop] = nCnt;
nLoop++;
nCnt = 0;
}
}
}
#자릿수가 다른 두 수의 합을 처리하고 싶었으나 두, 세 자릿수에서 부터 시작되는 올림의 영향을 처리하는 것에 실패하여 그냥 오류 메세지를 출력하도록 하였습니다. ㅠㅠ
def up(a, b):
r = 0
a = list(reversed(str(a)))
b = list(reversed(str(b)))
for i in range(max(len(a), len(b))):
try:
if int(a[i]) + int(b[i]) >= 10: r += 1
elif int(a[i]) + int(b[i]) == 9 and int(a[i-1]) + int(b[i-1]) >= 10: r += 1
except IndexError as e:
return e
return r
import numpy as np
a=int(input("첫번째 숫자를 입력하세요:"))
b=int(input("두번째 숫자를 입력하세요:"))
c=a+b
l_a=len(str(a)) #a의 자릿수
l_b=len(str(b)) #b의 자릿수
l_c=len(str(c)) #c의 자릿수
carry=0
tmp=0
for i in range(l_c):
if (a/(10**i)%10)+(b/(10**i)%10)>9:
carry=carry+1
tmp=1
elif (a/(10**i)%10)+(b/(10**i)%10)==9:
carry=carry+1
tmp=1
else:
tmp=0
print(carry, "carry operations")
import java.util.Scanner;
public class Primary_Arithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a;
int b;
int carry_counter;
int length;
while(true) {
a = sc.nextInt();
b = sc.nextInt();
carry_counter = 0;
if(a == 0 && b == 0)
break;
length = String.valueOf(a).length();
for(int i=0; i<length; i++) {
if(a%10 + b%10 >= 10) {
carry_counter++;
}
a /= 10;
b /= 10;
}
if(carry_counter == 0)
System.out.println("No carry operatio");
else
System.out.println(carry_counter + "carry operations");
}
sc.close();
}
}
a= input('숫자2개입력: 하나입력후 스페이스바후 다시입력').split(' ')
value3= int(a[0][-1])+int(a[1][-1])
value2= int(a[0][-2])+int(a[1][-2])
value1= int(a[0][-3])+int(a[1][-3])
carry=0
if value3 >=10:
value3 -= 10
carry +=1
value2 = value2 + 1 #자리수 올라감
if value2 >=10:
value2 -= 10
carry +=1
value1 = value1+1
if value1>=10:
carry +=1
if carry ==0:
carry='No'
print(carry,' carry operation.')
l1,l2,l3,result = [],[],[],[]
while True:
count = 0
numbers = raw_input()
if numbers == "0 0": break
else:
numbers = numbers.split(" ")
l1 = [int(x) for x in numbers[0]]
l2 = [int(x) for x in numbers[1]]
l3 = [int(x) for x in str(int(numbers[0]) + int(numbers[1]))]
count = [i for i in range(len(l1)) if l3.pop() < l1.pop()] if int(numbers[0]) > int (numbers[1]) else [i for i in range(len(l1)) if l3.pop() < l2.pop()]
result.append(count.pop()+1) if count else result.append(0)
for i in range(len(result)):
print("%s carry operation."% result[i])
n1 = '555'
n2 = '555'
tmp_n = ''
len_n1 = 0
len_n2 = 0
carry = 0
c_v = 0
if len_n2>len_n1:
tmp_n = n1
n1 = n2
n2 = tmp_n
len_n1 = len(n1)-1
len_n2 = len(n2)-1
while len_n1 >= 0 and len_n2 >= 0:
n1_v = int(n1[len_n1]) + c_v
n2_v = int(n2[len_n2])
if (n1_v+n2_v)>=10:
carry = carry + 1
c_v = (n1_v+n2_v) - 10
len_n1 = len_n1 - 1
len_n2 = len_n2 - 1
if carry == 0:
print('No carry operation.')
else:
print(str(carry)+' carry operation.')
# python 3.7.1
def get_carry(num1, num2):
while True:
if int(num1) == 0 and int(num2) == 0:
break
num1_int_list = list(map(int, [num for num in str(num1)]))
num2_int_list = list(map(int, [num for num in str(num2)]))
if len(num1_int_list) >= len(num2_int_list):
for i in range(len(num1_int_list) - len(num2_int_list)):
num2_int_list.insert(0, 0)
else:
for i in range(len(num2_int_list) - len(num1_int_list)):
num1_int_list.insert(0, 0)
count, carry = 0, 0
for i in list(num1 + num2 for num1, num2 in zip(reversed(num1_int_list), reversed(num2_int_list))):
i = i + carry
if i >= 10:
carry = 1
count = count + 1
if count == 0:
count = 'No'
print(str(count) + " carry operation.")
while 1:
nums = input()
if nums == "0 0":
break
else:
two_num = nums.split()
one = two_num[0]
two = two_num[1]
oper = 0
if int(one[2]) + int(two[2]) >= 10:
oper += 1
if int(one[1]) + int(two[1]) + 1 >= 10:
oper += 1
if int(one[0]) + int(two[0]) + 1 >= 10:
oper += 1
else:
if int(one[0]) + int(two[0]) >= 10:
oper += 1
else:
if int(one[1]) + int(two[1]) >= 10:
oper += 1
if int(one[0]) + int(two[0]) + 1>= 10:
oper += 1
else:
if int(one[0]) + int(two[0]) >= 10:
oper += 1
print(str(oper) + " carry operations")
def cal(no1,no2):
num = min(len(str(no1)),len(str(no2)))
cnt = 0
for aa in range(1,num+1):
ans1 = (no1 % (10**aa)) // (10**(aa-1))
ans2 = (no2 % (10**aa)) // (10**(aa-1))
if ans1 + ans2 >= 10:
cnt +=1
return cnt
ans_list= list()
def main():
while True:
num1 = int(input())
num2 = int(input())
print('\n')
if num1 == 0 and num2 == 0:
break
else:
cal(num1,num2)
ans_list.append(cal(num1,num2))
for char in abc:
if int(char) == 0:
print('No carry operation.')
else:
print('{} carry operation.'.format(char))
main()
Java 8
import java.util.ArrayList;
import java.util.List;
public class tut06 {
public static void main(String[] args) {
String input = "123 456 \r\n" + "555 555 \r\n" + "123 594 \r\n" + "0 0";
List<List<Integer>> list = new ArrayList<>();
int num1 = 0;
int num2 = 0;
int cnt;
char[] num1Chars;
char[] num2Chars;
// input을 4줄로 잘라낸다.
for (String s : input.split("\r\n")) {
List<Integer> tmpList = new ArrayList<>();
for (String r : s.split(" ")) {
tmpList.add(Integer.parseInt(r));
}
list.add(tmpList);
}
// 실제 계산
for (int i = 0; i < list.size() - 1; i++) {
num1 = list.get(i).get(0);
num2 = list.get(i).get(1);
num1Chars = (num1 + "").toCharArray();
num2Chars = (num2 + "").toCharArray();
cnt = 0;
for (int j = 0; j < num1Chars.length; j++) {
num1 = num1Chars[j] - '0';
num2 = num2Chars[j] - '0';
if (num1 + num2 >= 10) {
cnt++;
}
}
if (cnt > 0) {
System.out.println(cnt + " carry operations.");
} else {
System.out.println("No carry operation.");
}
}
}
}
문제 그대로
lis = []
while True:
inp = input().split()
if inp == ['0','0']:
break
lis.append(inp if int(inp[0]) > int(inp[1]) else list(reversed(inp)))
for x1,x2 in lis:
n = 0
x1,x2 = list(reversed(x1)),list(reversed(x2))
for x in range(len(x1)):
if eval('%s+%s' %(x1[x],x2[x] if len(x2) > x else '0')) >= 10:
n += 1
if len(x1) > x+1:
x1[x+1] = str(int(x1[x+1]) +1)
print(n)
함수
def Primary_Arithmetic(x1,x2):
n = 0
x2,x1 = list(sorted([x1,x2]))
x1,x2 = list(reversed(str(x1))),list(reversed(str(x2)))
for x in range(len(x1)):
if eval('%s+%s' %(x1[x],x2[x] if len(x2) > x else '0')) >= 10:
n += 1
if len(x1) > x+1:
x1[x+1] = str(int(x1[x+1]) +1)
print(n)
def get_carry_count(x, y):
if len(x) != len(y):
sys.exit('input is not the same length!')
length = len(x)
carry_cnt = 0
for i in range(length):
if 10 <= int(x[i]) + int(y[i]):
carry_cnt+= 1
return carry_cnt
for idx in range(len(input_set)):
cnt = get_carry_count(str(input_set[idx][0]), str(input_set[idx][1]))
print('%s carry operation.' %(str(cnt) if cnt > 0 else 'No'))
input_set = [[123, 456], [555, 555], [123, 594]]
def get_carry_count(x, y):
if len(x) != len(y):
sys.exit('input is not the same length!')
length = len(x)
carry_cnt = 0
for i in range(length):
if 10 <= int(x[i]) + int(y[i]):
carry_cnt+= 1
return carry_cnt
for idx in range(len(input_set)):
cnt = get_carry_count(str(input_set[idx][0]), str(input_set[idx][1]))
print('%s carry operation.' %(str(cnt) if cnt > 0 else 'No'))
S = []
while True:
a, b = map(int, input().split())
if (a, b) == (0, 0):
break
else:
S.append(a)
S.append(b)
def carry_op(a, b):
lim = len(max(str(a),str(b)))
a_str = str(a).zfill(lim)
b_str = str(b).zfill(lim)
a_bag = list( map(int, a_str))
b_bag = list( map(int, b_str))
a_bag.reverse()
b_bag.reverse()
temp = []
cnt = 0
for i in range(0, lim):
if i == lim - 1:
if a_bag[i] + b_bag[i] > 9:
cnt += 1
else:
num = a_bag[i] + b_bag[i]
if num > 9:
a_bag[i + 1] += 1
cnt += 1
if cnt == 0:
return 'No carry operation.'
elif cnt == 1:
return '1 carry operation.'
else:
return '{} carry operations.'.format(cnt)
for i in range(0, len(S), 2):
print(carry_op(S[i], S[i+1]))
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
Carry(123, 456);
Carry(555, 555);
Carry(123, 594);
Carry(0, 0);
}
static void Carry(int a, int b)
{
if (a == 0 && b == 0) Environment.Exit(0);
bool carry = false;
int carry_count = 0;
int max = 0;
if (a.ToString().Length > b.ToString().Length)
{
max = a;
}
else max = b;
for (int i = 0; i < max.ToString().Length; i++)
{
if (a % 10 + b % 10 >= 10)
{
if (carry == true)
{
carry_count += 2;
carry = true;
}
else
{
carry_count += 1;
carry = false;
}
a /= 10;
b /= 10;
}
else
{
carry = false;
a /= 10;
b /= 10;
}
}
if (carry_count > 0)
{
Console.WriteLine(carry_count + " carry operation");
}
else Console.WriteLine("no carry operation");
}
}
}
carry_operation_list = []
while True:
carry_operation = 0
a, b = input("숫자 입력하세요 : ").split()
if a == '0' and b == '0':
break
for count in range(len(a)):
if int(a[count]) + int(b[count]) >= 10:
carry_operation += 1
carry_operation_list.append(carry_operation)
print(carry_operation_list)
for carry_count in range(len(carry_operation_list)):
if carry_operation_list[carry_count] == 0:
print("None carry operation.")
else: print("%s carry operation." % carry_operation_list[carry_count])
my_list = []
num1=0
num2=0
in_count=0
add=0
carry=0
carry_count=0
while True:
in_str = input()
if in_str=='0 0':
break
my_list.append(in_str)
for i in my_list:
num1,num2 = i.split(' ')
while in_count<len(num1):
add = int(num1[in_count]) + int(num2[in_count]) + carry
carry=0
in_count+=1
if add>=10:
carry=add-9
carry_count+=1
if carry_count==0:
print("No carry operation.")
else:
print("%d carry operation."%carry_count)
carry_count=0
in_count=0
add=0
carry=0
먼저 입력된 수가 크다는 가정하에 코드를 짜 보았습니다.
def primary_arithmetic(n1, n2):
carry_operation = 0
x1, x2, alpha = 1, 1, 0
while x1 < len(n1)+1:
while x2 < len(n2)+1:
if alpha:
if int(n1[-x1])+int(n2[-x2])+1 >= 10:
alpha = 1
carry_operation += 1
else:
alpha = 0
else:
if int(n1[-x1])+int(n2[-x2]) >= 10:
alpha = 1
carry_operation += 1
else:
alpha = 0
x1 += 1
x2 += 1
if x2 == len(n2)+1:
x1 -= 1
if alpha:
if int(n1[-x1])+1 >= 10:
carry_operation += 1
alpha = 1
else:
alpha = 0
else:
if int(n1[-x1]) >= 10:
carry_operation += 1
alpha = 1
else:
alpha = 0
x1 += 1
return carry_operation
n1, n2 = input().split()
result = primary_arithmetic(n1, n2)
if result == 0:
print("/no carry operation.")
else:
print('%d carry operation' % result)
def priari(a, b):
stra = [int(str(a)[x]) for x in range (0, len(str(a)))];
strb = [int(str(b)[x]) for x in range (0, len(str(b)))];
diff = len(stra) - len(strb);
if diff > 0:
while diff > 0:
strb.insert(0,0);
diff = diff - 1;
elif diff < 0:
while diff < 0:
stra.insert(0,0);
diff = diff + 1;
carrynum = 0;
digitnum = 0;
temp = 0;
stra.reverse();
strb.reverse();
while digitnum < len(stra):
if stra[digitnum] + strb[digitnum] + temp > 9:
carrynum = carrynum + 1;
temp = 1;
digitnum = digitnum + 1;
return carrynum
print(priari(555,555))
x,y = map(str,(input("입력1:"),input("입력2:")))
sum = int(x) + int(y)
sum = str(sum)
sumList1=[0 for i in range(10-int(len(sum)))]
sumList2=list(sum)
sumList = sumList1 + sumList2
xList1=[0 for i in range(10-int(len(x)))]
xList2=list(x)
xList =xList1 + xList2
yList1=[0 for i in range(10-int(len(y)))]
yList2=list(y)
yList =yList1 + yList2
carry = 0
if x != '0' or y != '0':
for i in range(10):
if int(xList[i]) > int(sumList[i]) or int(yList[i]) > int(sumList[i]):
carry += 1
if carry == 1:
print("{} carry operation".format(carry))
elif carry > 1:
print("{} carry operations".format(carry))
elif carry <= 0:
print("No carry operation")
while 1:
q,w=map(str,input().split())
if q=='0' and w=='0':
break
q=list(q);q.reverse();w=list(w);w.reverse()
while len(q)!=len(w):
if len(q)>len(w):
w.append('0')
else:
q.append('0')
count=0
for i in range(len(q)):
if int(q[i])+int(w[i])+int(bool(count)) > 9:
count+=1
if count==0:
print("No carry operation.")
else:
print("{} carry operations.".format(count))
출제자님의 의도대로 입력받고 출력도 한번에 정리해서 내는 형태는아니지만... 그래도, bool형 변수를 충분히 이용할 수 있었던 문제인것같읍니다.
class Study
{
public static void main(String[] args)
{
int[][] arr = new int[10][6];
int[] carry= new int[10];
int x, y, count=0;
Scanner sc = new Scanner(System.in);
for(int i=0; i<10; i++) {
System.out.println("X값 입력: ");
x = sc.nextInt();
System.out.println("Y값 입력: ");
y = sc.nextInt();
//x입력
arr[i][0]=x/100;
arr[i][1]=(x/10)%10;
arr[i][2]=x%10;
//y입력
arr[i][3]=y/100;
arr[i][4]=(y/10)%10;
arr[i][5]=y%10;
if(x==0 && y==0)
break;
count++;
}
for(int i=0; i<count; i++){
for(int j=0; j<3; j++) {
if(arr[i][j]+arr[i][j+3] > 9)
carry[i]++;
}
}
System.out.println("ANSWER");
for(int i=0; i<count; i++){
if (carry[i] == 0) {
System.out.println("No carry operation. ");
}else {
System.out.println(carry[i] +"carry operation.");
}
}
}
}
def carry_num(m, n, count=0):
if m == 0 or n == 0:
print(count)
return
a = m % 10
b = n % 10
m = m // 10
n = n // 10
if a + b >= 10:
count += 1
m += 1
carry_num(m, n, count)
>>> carry_num(123, 456)
0
>>> carry_num(555, 555)
3
>>> carry_num(123, 594)
1
#include<stdio.h>
#include<math.h>
int hanjaliGet(int, int);
int main()
{
printf("두개의 숫자를 입력해주세요.\n");
int fnum = 0;
int snum = 0;
scanf_s("%d %d", &fnum, &snum);
printf("%d carry operations.\n", hanjaliGet(fnum, snum));
return 0;
}
int hanjaliGet(int fi, int se)
{
int sum = fi + se;
int count = 0;
for (int i = 1; pow(10,i) <= sum*10; i++)
{
int hap = (fi / (int)pow(10, i-1) % 10) + (se / (int)pow(10, i-1) % 10);
if (hap%10 != sum/(int)pow(10,i-1) % 10)
{
printf("%d, %d\n", hap % 10, sum / (int)pow(10, i-1) % 10);
count++;
}
}
return count;
}
//여러개 출력하는건 추후 수정 예정
def arithmetic(a,b):
while len(str(a))!=len(str(b)):
if int(a) > int(b) :
b = '0'+str(b)
else:
a = '0'+ str(a)
cnt = 0
for i,j in zip(str(a),str(b)):
print(i,j)
if len(str(int(i)+int(j))) > 1 :
cnt +=1
if cnt != 0:
print(cnt,'carry operation')
else:
print('No carry operation')
#include <iostream>
using namespace std;
void myGenerator(int a, int b)
{
int cnt = 0;
int A = a;
int B = b;
for (int i = 10; (A>0&&B >0); i = 10)
{
if ((A % i + B % i) > 9)
cnt++;
A = A / i;
B = B / i;
}
cout << cnt << endl;
}
int main()
{
int x, y;
cin >> x;
cin >> y;
myGenerator(x, y);
}
def Primary_Arithmetic(A, B):
n1 = str(A)
n2 = str(B)
carry = [0]
for i in range((len(n1), len(n2))[A<B]):
if carry[i]+int(n1[-i-1])+int(n2[-i-1]) >= 10: carry.append(1)
else: carry.append(0)
return carry.count(1)
def run():
carry = []
while 1:
A, B = map(int, input('>>>').split(' '))
if A == 0 and B == 0: break
carry.append(Primary_Arithmetic(A, B))
for i in range(len(carry)):
if carry[i] == 0: print('No carry operation.')
elif carry[i] == 1: print(carry[i], 'carry operation.')
else: print(carry[i], 'carry operations.')
이정도면 그냥 파이썬이 아닌데..
def carry():
lst = []
while True:
k = input("A와 B의 값을 입력하세요")
lst.append(k)
if lst[-1] == '0 0':
lst.pop()
break
for i in lst:
carry_ = 0
lst2 = i.split()
print(lst2)
if len(lst2[0]) >= len(lst2[1]):
digit = len(lst2[0])
else:
digit = len(lst2[1])
for j in range(digit,0,-1):
if int(lst2[0][-j]) + int(lst2[1][-j]) > 9:
carry_ += 1
print(f'{carry_} carry operation')
carry()
def sum_carry(X11, X22):
X1, X2 = list(X11), list(X22)
if len(X1) > len(X2):
num_big = X1
num_small = X2
else:
num_big = X2
num_small = X1
#num_small[0:0] = ['0']*(len(num_big)-len(num_small))
carry = 0
car_cnt = 0
for i in reversed(range(len(num_big))):
digit_sum = int(num_big[i]) + int(num_small[i]) + carry
if digit_sum >= 10:
carry = 1
car_cnt += 1
else:
carry = 0
return car_cnt
X1, X2 = input().split()
result = sum_carry(X1, X2)
print("{} carry operation.".format(result if result != -1 else 'No'))
a,b=input("양의 정수 두 개 입력: ").split(' ')
c,d=input("0 두 개 입력: ").split(' ')
carry=0
i=-1
while i>=min([len(a),len(b)])*(-1):
if int(a[i])+int(b[i])>=10:
carry +=1
i=i-1
if carry==0:
print("No carry operation")
else:
print("%d carry operations" %carry)
x=input()
y=input()
listx=[]
listy=[]
for i in x:
listx.append(int(i))
for i in y:
listy.append(int(i))
sx=int(x)+int(y)
listsum=[]
result=0
for i in str(sx):
listsum.append(int(i))
t=0
for i in listx:
t+=1
x=listx[-t]
y=listy[-t]
s=listsum[-t]
print(x,y,s)
if s<(x+y):
result+=1
if result==0:
print('No carry operation.')
if result!=0:
print(result,'carry operation.')
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
vector<string> inputs = { "123 456","555 555","123 594","0 0" };
int pa(int n1, int n2);
int main() {
int operand[2] = { 0 };
for (int l = 0; l< inputs.size(); l++) {
for (int i = 0, pos = 0; i < inputs[l].size(); i++) {
if (inputs[l][i] == ' ') {
pos++;
continue;
}
operand[pos] = operand[pos] * 10 + inputs[l][i]- 48;
}
if (operand[0] == 0 && operand[0] == operand[1]) break;
int t = pa(operand[0], operand[1]);
operand[0] = operand[1] = 0;
if (t == 0) cout << "no";
else cout << t;
cout << " carry operation."<< endl;
}
return 0;
}
int pa(int n1, int n2) {
int c = 0;
int answer = 0;
while (n1 > 0 && n2 > 0) {
int a = n1 % 10;
int b = n2 % 10;
if (a + b + c > 9) {
c = 1;
}
else {
c = 0;
}
n1 /= 10, n2 /= 10;
answer += c;
}
return answer;
}
PHP
$fn = function(int $i, int $j) : string {
$cnt = 0;
$len = strlen(strval($i + $j));
$arr = [
array_reverse(str_split(sprintf("%0{$len}d", $i))),
array_reverse(str_split(sprintf("%0{$len}d", $j))),
];
foreach (range(1, $len) as $k => $v) {
if ($arr[0][$k] + $arr[1][$k] >= 10) ++$arr[0][$k + 1] && ++$cnt;
}
return ($cnt === 0 ? 'No' : strval($cnt)).' carry operation'.($cnt > 1 ? 's' : '').'.';
};
print_r($fn(123, 456)); // No carry operation.
print_r($fn(555, 555)); // 3 carry operations.
print_r($fn(123, 594)); // 1 carry operation.
data = list(input("숫자를 입력하세요 : ").split(" "))
first_num = data[0]
second_num = data[1]
min_value = len(min(data))
count = 0
for i,j in zip(first_num[-min_value:],second_num[-min_value:]):
if int(i)+int(j) >= 10:
count += 1
print(count, "Carry operation")
def numOfCarryOp(x, y):
carries = 0
carryOperation = 0
while x > 0 or y > 0:
x1 = x % 10
y1 = y % 10
if (carries + x1 + y1) >= 10:
carries = 1
carryOperation += 1
else:
carries = 0
x = (x - x1) / 10
y = (y - y1) / 10
return carryOperation
[x, y] = map(int, input("Enter two numbers\nex. \n12 999\n: ").split())
carryOperation = numOfCarryOp(x, y)
result = " carry operaton"
if carryOperation == 0:
result = "no" + result
elif carryOperation == 1:
result = "1" + result
else:
result = str(carryOperation) + result + "s"
print(result)
#Primary Arithmetic
value = input("두 수 입력 : ")
n1,n2 = value.split(" ")
carry = 0
temp = 0
for i in range(1,min(len(n1),len(n2))+1):
if int(n1[-i]) + int(n2[-i]) + temp >= 10 :
print(n1[-i],n2[-i])
temp = 1
carry += 1
else :
continue
print("{} carry operations".format(carry))
import java.util.*;
public class PrimaryArithmetic {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> nums = new ArrayList<String>();
while(true) {
int i=0;
String line = scan.nextLine();
String[] lines = line.split(" ");
if(line.equals("0 0")) {
break;
}
else {
nums.add(lines[i]);
nums.add(lines[i+1]);
lines = null;
}
}
for(int j=0; j<nums.size(); j=j+2) {
int count = 0;
String[] a = nums.get(j).split("");
String[] b = nums.get(j+1).split("");
int[] arr1 = Arrays.stream(a).mapToInt(Integer::parseInt).toArray();
int[] arr2 = Arrays.stream(b).mapToInt(Integer::parseInt).toArray();
reverse(arr1);
reverse(arr2);
값구하기(arr1, arr2);
arr1=null;
arr2=null;
a=null;
b=null;
}
}
private static void reverse(int[] arr) {
int[] arrReverse = new int[arr.length];
for(int s = 0; s<arr.length; s++) {
arrReverse[arr.length-1-s] = arr[s];
}
for(int d = 0; d<arr.length; d++) {
arr[d] = arrReverse[d];
}
}
private static void 값구하기(int[] array1, int[] array2) {
int count = 0;
int w = 0;
if(array1.length==array2.length) {
for(int k = 0; k<array1.length; k++) {
int n = 0;
n= array1[k]+array2[k]+w;
if(n>=10) {
count++;
w=1;
}
else if(n<10) {
w=0;
}
}
}
if(array1.length>array2.length) {
for(int k = 0; k<array2.length; k++) {
if(array1[k]+array2[k]>=10) {
count++;
for(int p = 1; p<array1.length; p++) {
if(array2[p]+1>=10) {
count++;
}
}
}
}
}
if(array1.length<array2.length) {
for(int k = 0; k<array1.length; k++) {
if(array1[k]+array2[k]>=10) {
count++;
for(int q = 1; q<array2.length; q++) {
if(array2[q]+1>=10) {
count++;
}
}
}
}
}
if(count==0) {
System.out.println("No carry operation.");
}
else {
System.out.println(count+" carry operations.");
}
} }
//.......1 99999 같은 경우도 값이 나올 수 있게 만들었습니다.....하...복잡하네요.. ```
파이썬 3.6 입니다
def primary_arithmetic(a, b):
a_str = str(a)
b_str = str(b)
# 입력 된 두 숫자의 자리수가 다를 경우 앞에 0을 추가 후 비교
if len(a_str) > len(b_str):
b_str = b_str.zfill(len(a_str))
elif len(a_str) < len(b_str):
q_str = a_str.zfill(len(b_str))
sum_result_each_digit = [int(i[0]) + int(i[1]) for i in zip(a_str, b_str)]
operation_count = len([x for x in sum_result_each_digit if x >= 10])
print(f"{operation_count} carry operation")
print(primary_arithmetic(123, 456))
print(primary_arithmetic(555, 555))
print(primary_arithmetic(123, 594))
# 두 자연수를 입력받아 num1, num2에 저장
A = input("숫자를 입력하세요.(abc def) :",)
num1, num2 = A.split(' ')[0][::-1], A.split(' ')[1][::-1]
# 두 자연수 중 큰 수를 num1에 저장
if int(num1) < int(num2):
base = num1
num1 = num2
num2 = base
# 각 자연수의 자릿수를 1의자리부터 list로 저장
# 자릿수가 다른 경우를 대비하여 작은 숫자인 num2에 부족한만큼 0을 추가
a_num1 = [int(i) for i in num1]
a_num2 = [int(i) for i in num2] + [0]*(len(num1)-len(num2))
## 자릿수별 연산 시작 ##
carry = 0
upper = 0
for i in range(0,len(a_num1)):
if int(a_num1[i]) + int(a_num2[i]) + upper > 9:
upper = 1
carry += 1
else:
upper = 0
if carry == 0:
print("No carry operation.")
elif carry == 1:
print("1 carry operation.")
else:
print("%d carry operations." %carry)
a = list(map(int, input("입력: ")))
b = list(map(int, input("입력: ")))
result = 0
if len(a) > len(b):
for i in range(0, len(b)):
if a[i+(len(a)-len(b))]+b[i] >= 10:
result += 1
if a[i+(len(a)-len(b))]+b[i] >= 10 and a[i+(len(a)-len(b))+1] +== 9:
if a[0] == 9:
result += 1
elif len(b) > len(a):
for i in range(0, len(a)):
if b[i+(len(a)-len(b))]+a[i] >= 10:
result += 1
if b[0] == 9:
result += 1
elif len(a) == len(b):
for i in range(0, len(a)):
if a[i]+b[i] >= 10:
result += 1
print("{} carry operation!".format(result))
'''
1255+ 345 생각
1255+ 45 생각
9999+9999 생각
'''
while True:
i = input("Enter the number:")
a = i.split(' ')
b =[int(c) for c in (str(a[0]))]
b_leng = len(b)
d =[int(e) for e in (str(a[1]))]
d_leng = len(d)
k = 0
if i == '0 0' or max(b_leng,d_leng) >= 10:
break
else:
for j in range(0,min(b_leng,d_leng)):
if (b[j]) + (d[j]) >= 10:
k = k+1
else:
continue
print(k, 'carry operation')
a,b=map(int,input("input same digits numbers>>>").split())
while a or b: if a>b: longer=len(str(a)) shorter=len(str(b)) else: longer=len(str(b)) shorter=len(str(b)) carry=carry_num=num=0 if a==0 or b==0:shorter=0 while shorter>0: if a>b:num+=int(str(a)[longer-1])+int(str(b)[shorter-1])+carry_num else:num+=int(str(a)[shorter-1])+int(str(b)[longer-1])+carry_num if num>=10: carry_num=1 carry+=1 else:carry_num=0 shorter-=1 longer-=1 num=0 while longer>0: if a>b:num+=int(str(a)[longer-1])+carry_num else:num+=int(str(b)[longer-1])+carry_num if num>=10: carry_num=1 carry+=1 else:carry_num=0 longer-=1 num=0
if carry==0:print("No carry operation.")
elif carry==1:print("1 carry operation.")
else:print("%d carry operations."%carry)
a,b=map(int,input("input same digits numbers>>>").split())```{.python}
Python 3.8 입니다. 초보자라 이해부탁드려요~~^^ ```
a='''123 896
555 5554
999999 1
123 456
100 900
0 0'''
n=0
l=a.split('\n')#a를 줄바꿈 기준으로 나누어 리스트화
del l[-1]#0 0 제외.
for i in l:#l 각각의 쌍에 대하여
z=i.split()#쌍을 전자 후자로 나눔.
x=[int(i) for i in z[0]]#전자를 숫자형으로 바꾸고 역순 리스트화.
x.reverse()
y=[int(i) for i in z[1]]#후자를 숫자형으로 바꾸고 역순 리스트화.
y.reverse()
if len(x)>len(y):#전자의 길이가 후자보다 길면,
for i in range(len(y)):# 짧은 길이만큼 반복
if x[i]+y[i]>=10:#더해서 10보다 크면,
x[i+1]+=1#긴쪽의 다음 원소(자릿수 큰 쪽)에 1을 더한다.
n+=1#올림 횟수를 n에 기록
else:
pass
for i in range(len(y),len(x)-1):
'''전자의 길이가 더 기니까 남은 부분의 올림 횟수 기록.
단, x의 마지막 원소는 들어가지 않도록'''
if x[i]>=10:
x[i+1]+=1
n+=1#기록
else:
pass
if x[-1]>=10: #x의 마지막 원소.
n+=1#기록
elif len(y)>len(x):
for i in range(len(x)):
if x[i]+y[i]>=10:
y[i+1]+=1
n+=1
else:
pass
for i in range(len(x),len(y)-1):
if y[i]>=10:
y[i+1]+=1
n+=1
else:
pass
if y[-1]>=10:
n+=1
else:
for i in range(len(y)-1):#마지막 원소 제외하고 판단 하도록.
if x[i]+y[i]>=10:
x[i+1]+=1
n+=1
else:
pass
if x[-1]+y[-1]>=10:
n+=1
else:
pass
if n==0:
print('No carry operation.')
elif n==1:
print('1 carry operation.')
else:
print(str(n)+' carry operations.')
n=0
파이썬 입니다~^^
res_str = ''
t_count = 0
for i in range(10):
count=0
try:
s_num1, s_num2 =input('{}번째: 숫자 두개를 입력하세요(예: 123 345, 종료를 원하면 0 0을 입력)'.format(t_count+1)).split()
except Exception as ex:
print('숫자 두개를 입력하여야 합니다 다시시작해주세요', ex)
break
if not s_num1.isdigit() or not s_num2.isdigit():
print('숫자를 입력하여야 합니다 다시 시작해주세요')
break
if ((s_num1=='0') and (s_num2=='0')) or t_count==10:
break
back_num1 = s_num1[::-1]
back_num2 = s_num2[::-1]
for i in range(min(len(s_num1), len(s_num2))-1, -1, -1):
if int(back_num1[i:i+1]) + int(back_num2[i:i+1]) >= 10:
count += 1
if count==0:
res_str = res_str + 'No carry operation.' + '\n'
else:
res_str = res_str + '{} carry operations.'.format(count) + '\n'
t_count += 1
print(res_str)
코딩을 잘하지 못하다 보니 오류 발생하는 부분을 제어하려다 보니 if문을 많이 추가하게 되었네요 ^^;;
i,b=0,[]
while (i<10):
a=input().split(' ')
if a[0]=='0' and a[1]=='0':
break
b.append(a)
i+=1
for i in range (len(b)):
c,s=0,[]
for j in range (0,len(b[i][0])):
s.append(int(b[i][0][j])+int(b[i][1][j]))
j=len(s)-1
while (j>-1):
if s[j]>9:
s[j],c=s[j]-10,c+1
if s[j]!=0:
s[j-1]+=1
j-=1
print ('carry operation : ',c)
num=[]
s = ''
i,left,right = 0,0,0
while i<10 :
s = input()
if (s == '0 0') : break
num.append(s)
i += 1
for i in range(len(num)) :
carry, up = 0,0
a = list(map(int,num[i].split(' ')))
left, right = a[0], a[1]
for j in range(max(len(str(left)),len(str(right)))) :
if (left%10) + (right%10) + up >= 10 :
up = 1
carry += 1
else : up = 0
left //= 10
right //= 10
if carry == 0 : print('No carry operation')
elif carry == 1 : print('1 carry operation')
else : print('%d carry operations' %carry)
num_one=input("더하기를 수행할 첫번째 숫자 : ")
num_two=input("더하기를 수행할 두번재 숫자 : ")
carry=0
if len(num_one)>len(num_two):
max=len(num_one)
a=len(num_one)-len(num_two)
b=0
else:
max=len(num_two)
a=0
b = len(num_two) - len(num_one)
for i in range(max-1,-1,-1):
if i - a <0 or i - b <0:
break
cur=int(num_one[i-b])+int(num_two[i-a])
if cur>=10:
carry+=1
print("{} carry operation".format(carry))
a = str(input())
b = str(input())
if int(a)<=int(b):
b = b.zfill(len(b)+1)
a = a.zfill(len(b))
else:
a = a.zfill(len(a)+1)
b = b.zfill(len(a))
sum = 0
for i in range(1,len(max(a,b))+1):
if int(a[-i])+int(b[-i]) >=10:
sum += 1
if a[-i-1] == '9':
b = b.replace(b[-i-1],str(int(b[-i-1])+1))
elif b[-i-1] == '9':
a = a.replace(a[-i-1],str(int(a[-i-1])+1))
else:
continue
if sum == 0:
print("No carry operation")
else:
print("%d carry operation"%sum)
zfill을 한 번 이용해봤습니다~
a = input('input the first number: ')
b = input('input the second number: ')
if len(a)>len(b): no_digit = len(b)
else: no_digit = len(a)
carry = 0
for i in range(1,no_digit+1):
if int(a[-i])+int(b[-i]) > 9:
carry += 1
if len(a) > i & len(b) > i:
if int(a[-i-1])+int(b[-i-1]) == 9:
carry += 1
print(carry, " carry operation.")
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a,b;
int[] plus1 = new int[3];
int[] plus2 = new int[3];
int result =0;
while(true)
{
result=0;
a= scan.nextInt();
b= scan.nextInt();
if(a==0&&b==0)
break;
plus1[2] = a%10;
plus1[1] = (a/10)%10;
plus1[0] = (a/100)%10;
plus2[2] = b%10;
plus2[1] = (b/10)%10;
plus2[0] = (b/100)%10;
for(int i=0;i<3;i++)
{
if((plus1[i]+plus2[i])>=10)
result++;
}
System.out.println(result + " carry operations");
}
}
}
L=list()
while True:
n=input("> ")
L.append(n)
if n=='0 0':
break
L.pop()
L=[i.split() for i in L]
for i in L:
if len([j for j in [int(i[0][j])+int(i[1][j]) for j in range(len(i[0]))] if j>=10])==0:
print('No carry operation')
else:
print(str(len([j for j in [int(i[0][j])+int(i[1][j]) for j in range(len(i[0]))] if j>=10]))+' carry operation.')
자릿수가 서로 다른 수도 가능하게 수정해봤습니다ㅏ
package test;
import java.util.*;
public class Test{
public static void main(String[] args) {
int i = 1; int j = 0; int carry = 0; int count = 0;
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
while(count < Integer.toString(Math.max(a, b)).length()+1) {
if((a/i)%10 + (b/i)%10 + j>=10) {
carry++;
i*=10;
j=1;
}
else if((a/i)%10 + (b/i)%10 + j<10) {
i*=10;
j=0;
}
count ++;
}
if(carry == 0)
System.out.println("No carry operation.");
else if(carry > 0)
System.out.println(carry+" carry operations.");
else if(carry == 1){System.out.println("1 carry operation.");}
}
}
def primaryArithmetic(a,b):
result = 0
for i in range(0,min(len(str(a)), len(str(b)))):
if int(str(a)[i]) + int(str(b)[i]) > 9:
result += 1
if result == 0:
result = "No"
print("{} carry operations".format(result))
primaryArithmetic(123,456)
primaryArithmetic(555,555)
primaryArithmetic(123,594)
def pri(text):
temp_1 = text.split()[0]
temp_2 = text.split()[1]
_co = 0
for i in range(len(temp_1)):
if int(temp_1[i]) + int(temp_2[i]) >= 10:
_co += 1
if _co == 0:
_co = 'No'
return print('{} carry operations.'.format(_co))
pri(input('input : '))
def Primary_Arithmetic():
lists=[]
while True:
count=0
word=input("write word for cal EX)XXX YYY :")
words=word.split(" ")
if words[0]=='0' and words[1]=='0':
break
a=int(words[0])
b=int(words[1])
circle=0
c=0
while a>0 or b>0:
circle+=1
if a%10+b%10+c%10>=10:
count+=1
c+=10**1
a=a//10
b=b//10
c=c//10
lists.append(count)
for q in lists:
print("{0} carry operation".format(q))
조건에 만족하지 않는 요소가 몇 가지가 있습니다.
1. 여러 개의 값을 입력하지 못하고 두 수를 입력하면 바로 답을 출력한다.
2. 그에 따라 0 0 을 입력하면 입력콘솔이 종료되고 출력이 되는 것이 안된다.
이 것을 제외하면 나머지는 정상적으로 돌아갑니다.
1+99999 같은 것들도 정상적으로 돌아갑니다.
알고리즘은
숫자를 입력받고 배열에 넣습니다. 배열에 넣는 방식은 예를 들어 1234 를 입력받으면
0000001234 (0이 6개) 의 식으로 넣게 되어있습니다.
(이제부터 편의상 0을 생략하겠습니다)
01234
05678
이 두 수를 더할 때 4와 8 부터 시작해서 이 두 수의 합이 10이상이면 count를 1 올려주고 그 다음 자리수에 1을 더해줍니다. 그게 01234인지 05678 인지는 상관이 없으므로 아무꺼나 올려줍니다. 01298 일 때 만일 첫 번째 자릿수에서 carry가 발생한다면 두 번째 부분인 9 부분이 10으로 되니깐 안되지 않나 라고 생각하실 수도 있지만 01298은 말했다시피 배열이라서 arr[3]=10 라고 생각하실 수 있겠습니다.
#include <iostream>
#include <vector>
#define LEN 10
using namespace std;
int arrnum1[LEN];
int arrnum2[LEN];
int getLength(int);
void pushNum(int, int, int);
void reverseAll();
void swap(int&, int&);
void print(int);
void printarr(int*, int);
int getAnswer();
int main() {
int Num1, Num2;
int Numsize1, Numsize2;
cin >> Num1 >> Num2;
Numsize1=getLength(Num1);
Numsize2=getLength(Num2);
pushNum(Num1, Numsize1, 1);
pushNum(Num2, Numsize2, 2);
reverseAll();
int carry=getAnswer();
print(carry);
return 0;
}
int getAnswer() {
int carry=0;
for(int i=LEN-1;i>=0;i--) {
if((arrnum1[i]+arrnum2[i]) >=10) {
arrnum1[i-1]++;
carry++;
}
}
return carry;
}
int getLength(int num) {
int count=0;
while(num!=0) {
num/=10;
count++;
}
return count;
}
void pushNum(int num, int size, int what) {
if(what==1) {
for(int i=0;i<size;i++) {
arrnum1[i]=num%10;
num/=10;
}
for(int i =size;i<LEN;i++)
arrnum1[i]=0;
}
if(what==2) {
for(int i=0;i<size;i++) {
arrnum2[i]=num%10;
num/=10;
}
for(int i =size;i<LEN;i++)
arrnum2[i]=0;
}
}
void reverseAll() {
int temp;
for(int i=0;i<LEN/2;i++) {
temp = arrnum1[i];
arrnum1[i]=arrnum1[LEN-1-i];
arrnum1[LEN-1-i]=temp;
}
for(int i=0;i<LEN/2;i++) {
temp = arrnum2[i];
arrnum2[i]=arrnum2[LEN-1-i];
arrnum2[LEN-1-i]=temp;
}
}
void swap(int& a, int& b) {
int tmp=a;
a=b;
b=tmp;
}
void print(int num) {
if(num==0) {
cout << "No carry operation." << endl;
}
else if (num==1) {
cout << "1 carry operation." << endl;
}
else {
cout << num << " carry operations." << endl;
}
}
a, b = input().split()
c = 0
if(len(a) != len(b)):
if(int(a) < int(b)):
a,b =b,a
b = "0"*(len(a) - len(b)) + b
a = list(map(int,a))
b = list(map(int,b))
else:
a = list(map(int,a))
b = list(map(int,b))
for i in range(0,len(a)):
if(a[(len(a) -1) - i] + b[(len(b) - 1) - i] >= 10):
if(i == len(a) -1 ):
c +=1
else:
a[(len(a) -1) - (i+1)] += a[(len(a) -1) - i] + b[(len(b) - 1) - i] // 10
c +=1
if(c == 0):
print("No carry operation")
else:
print("%d carry operation" %c)
코드가 지저분하네요ㅠㅠ 깔끔하게 짜고싶다
def carry(data):
for x in data:
x1 = list(reversed(str(x[0])))
x2 = list(reversed(str(x[1])))
operation = False
count = 0
Range = len(x1) if len(x1)<len(x2) else len(x2)
for i in range(Range):
if i==0:
if int(x1[i])+int(x2[i])>9:
count+=1
operation =True
else :
if int(x1[i])+int(x2[i])>9 or (int(x1[i])+int(x2[i])==9 and operation==True):
count+=1
else :
operation = False
if count==0:
print('No carry operation')
elif len(x1)==len(x2):
if count==1:
print('{} carry operation'.format(count))
else :
print('{} carry operations'.format(count))
else :
if Range==len(x1):
for i in range(Range,len(x2)):
if int(x2[i])<9:
if count==1:
print('{} carry operation'.format(count))
else :
print('{} carry operations'.format(count))
break
else :
count+=1
if i==len(x2)-1:
print('{} carry operations'.format(count))
else :
for i in range(Range,len(x1)):
if int(x1[i])<9:
if count==1:
print('{} carry operation'.format(count))
else :
print('{} carry operations'.format(count))
break
else :
count+=1
if i==len(x1)-1:
print('{} carry operations'.format(count))
import numpy as np
data = np.array([[123,456],[555,555],[123,594],[99999,1]])
carry(data)
def count_operation(i,j):
i_reverse_list=list(map(int,list(str(i))))[::-1]
j_reverse_list=list(map(int,list(str(j))))[::-1]
cnt=0
for n in range(1,len(str(i))+1):
if n==1:
if i_reverse_list[0]+j_reverse_list[0]>=10:
cnt+=1
if n==2:
if i_reverse_list[n-1]+j_reverse_list[n-1]>=10:
cnt+=1
elif i_reverse_list[n-1]+j_reverse_list[n-1]==9 and \
i_reverse_list[n-2]+j_reverse_list[n-2]>=10:
cnt+=1
if n>=3:
if i_reverse_list[n-1]+j_reverse_list[n-1]>=10:
cnt+=1
elif i_reverse_list[n-1]+j_reverse_list[n-1]==9 and \
i_reverse_list[n-2]+j_reverse_list[n-2]>=10:
cnt+=1
elif i_reverse_list[n-1]+j_reverse_list[n-1]==9 and \
i_reverse_list[n-2]+j_reverse_list[n-2]==9 and \
i_reverse_list[n-3]+j_reverse_list[n-3]>=10 :
cnt+=1
return cnt
print(count_operation(1111,9579))
// * Primary Arithmetic
// * 추가적으로 자릿 수 상관없이 구현
let countCarry=0;
while(true){
countCarry=0;
const inputAry=prompt('정수 두개를 띄어쓰기로 구분하여 입력, 종료시 0 0 입력','').split(' ');
if(inputAry[0]==0 && inputAry[1]==0)
break;
/*numAry=inputAry.map((el)=>Number(el));
let sum= numAry.reduce((prev,cur)=>{
return prev + cur;
})
*/
let divAry1 = inputAry[0].split('');
let divAry2 = inputAry[1].split('');
divAry1.length>divAry2.length ? divAry2=addAry(divAry1,divAry2) : divAry1=addAry(divAry2,divAry1);
divAry1=divAry1.map((el)=>Number(el));
divAry2=divAry2.map((el)=>Number(el));
for (let i = divAry1.length; i >=0; i--) {
(divAry1[i]+divAry2[i]>=10) && cntCarry(i,divAry1);
}
//console.log(numAry)
countCarry==0 ?console.log('No carry operation.'):console.log(countCarry+' carry operation.')
}
function addAry(ary1,ary2){
addLength=ary1.length-ary2.length;
for (let i = 0; i < addLength; i++) {
ary2.unshift('0');
}
return ary2;
}
function cntCarry(i,divAry1){
i!=0 &&divAry1[i-1]++;
countCarry++;
}
def check(num1, num2):
carry = 0
temp = 0
while num1 != 0:
a = num1 % 10
b = num2 % 10
if a + b + carry > 9:
temp += 1
carry = 1
else:
carry = 0
num1 = num1 // 10
num2 = num2 // 10
return temp
temp2 = []
temp3 = []
while True:
temp = []
a, b = map(int, input('enter two intergers: ').split())
if a + b == 0:
break
else:
temp.append(a)
temp.append(b)
temp2.append(temp)
for i in temp2:
temp3.append(check(i[0], i[1]))
for i in temp3:
print('The number that carry occured: {}'.format(i))
a="555 555"
b= a.split(" ")
tot =0
A=[]
B=[]
for i in range(0,len(b[0])):
A.append(int(a[i]))
for q in range(0,len(b[1])):
B.append(int(a[q+len(b[0])+1]))
for i in range(len(A)):
if A[i]+B[i] >= 10:
tot+=1
print("%d"%tot)
numList = []
result = ""
# 숫자를 받는다
while True:
num = input("수를 입력하세요(ex.123 456) : ").split()
if sum(map(int,num)) == 0:
break
numList.append(num)
for x in numList:
a, b = x[0], x[1]
count = 0
# 자리수가 서로 다르다면
if len(a) != len(b):
# a의 자리수가 더 많을 경우
if len(a) > len(b):
# zfill : 자리수가 서로 다를 경우 빈 자리는 0으로 채워넣는다.(같은 인덱스를
서로 더해서 비교하기때문에)
a = a.zfill(len(a)+1) # 인덱스 범위 에러 방지위해 +1를 함
b = b.zfill(len(a))
for i in range(len(a)-1,-1,-1):
if (int(a[i]) + int(b[i]) >= 10):
b = str(int(b) + 10**(len(b) - i)).zfill(len(a))
count += 1
else:
pass
# b의 자리수가 더 많을 경우
else:
b = b.zfill(len(b)+1)
a = a.zfill(len(b))
for i in range(len(a)-1, -1, -1):
if (int(a[i]) + int(b[i]) >= 10):
a = str(int(a) + 10 ** (len(a) - i)).zfill(len(b))
count += 1
else:
pass
# 문자열 길이가 같다면
else:
for i in range(len(a)-1, -1, -1):
if (int(a[i]) + int(b[i]) >= 10):
count += 1
else:
pass
result += "%d carry operation\n" % (count)
print(result)
x='''123 456\n555 555\n123 594\n0 0'''
lines=x.split('\n')
count=0
for n in lines:
xlist=n.split(' ')
if xlist[0] == '0':
break
for i in range(len(xlist[0])):
if int(xlist[0][i]) + int(xlist[1][i]) >= 10:
count += 1
if count == 0:
print('No carry operation.')
elif count == 1:
print('1 carry operation.')
else:
print('{} carry operations.'.format(count))
count=0
문제를 정확하게 이해하지 못해서, 예시 기준으로 코드를 짰습니다.
#include <stdio.h> // printf, scanf_s
#include <math.h> // pow
int count_carry(int a, int b);
int main() {
int x, y;
int result;
printf("다섯자리 이하 정수 두 개 입력 : ");
scanf_s("%d %d", &x, &y);
result = count_carry(x, y);
printf("Carry : %d", result);
return 0;
}
int count_carry(int a, int b) {
int cnt=0, tmp=0;
int i;
int c, d;
for (i = 0; i < 5; i++) {
c = (a % (10 * (int)pow(10, i))) / (1 * (int)pow(10, i)); //일의 자리 ~ 만의 자리
d = (b % (10 * (int)pow(10, i))) / (1 * (int)pow(10, i)); //일의 자리 ~ 만의 자리
if (cnt + c + d > 9) {
cnt = 1;
tmp++; // carry + 1
}
else cnt = 0;
}
return tmp; // carry 반환
}
C언어로 작성했습니다.
ef makeAns(str1):
list1 = str1.split("\n")
i = 0
while True:
if list1[i] == "0 0":
break
else:
list2 = list1[i].split(" ")
len1 = min(len(list2[0]), len(list2[1])) # 더하는 값중 길이가 짤은 값을 구함 (문제는 3세자리의 합이지만 길이가 다른 수를 더할때도 작동하기 위해)
carry = 0
list2[0] = [str_ for str_ in list2[0]] # 더하는 값1 역순으로 배열 만듬
list2[0].reverse()
list2[1] = [str_ for str_ in list2[1]] # 더하는 값2 역순으로 배열 만듬
list2[1].reverse()
for j in range(0, len1):
if int(list2[0][j]) + int(list2[1][j]) >= 10:
carry += 1
if carry == 0:
carry = "No"
print(str(carry) + " carry operation")
i += 1
tmp = """123 456
555 555
123 594
0 0
"""
makeAns(tmp)
결과
No carry operation
3 carry operation
2 carry operation
a,b = input().split()
def counting_arithmatic(a,b):
if len(a) != len(b):
longer_no = max(len(a),len(b))
if len(a) == longer_no:
b = '0'*(longer_no-len(b))+b
else:
a = '0'*(longer_no-len(a))+a
print(a,b)
temp = 0
carry = 0
for c,d in zip(a[::-1],b[::-1]):
if 10 <= int(c)+int(d)+temp:
temp=1
carry += 1
else:
temp = 0
return carry
counting_arithmatic(a,b)
times = 0
a, b = input().split(' ')
c = [int(i) for i in a]
d = [int(j) for j in b]
x = [sum(n) for n in zip(c,d)]
for i in x:
if i >= 10: times += 1
elif 0 < i < 10: times += 0
if times > 1: print(times,"carry operations.")
elif times == 1: print("1 carry operation.")
elif times == 0: print("No carry operation.")
while문을 넣었고 split을 썼더니 계속
ValueError: not enough values to unpack (expected 2, got 1)이 떠서 결국 마지막 문장을 0,0으로 만드는건 구현을 못했네요 ㅜㅠㅠ 혹시 왜 오류나는지 아시는분은 가르쳐주세요 ㅜㅠㅠ
#codingdojing_primary arithmetic
from itertools import zip_longest
while True:
num1, num2 = input().split() # 123 1234
num1, num2 = num1[::-1], num2[::-1] # 321 4321
c_operation = 0
flag = 0
if (num1, num2) == ('0','0'):
print('end')
break
for a, b in zip_longest(num1, num2, fillvalue = 0): # 3210 4321 // 0123 1234 앞 자리수 채워주기
if int(a)+int(b)+c_operation > 9:
c_operation = 1 #올려서 다음자리 수 계산에 사용
flag += 1
else:
c_operation = 0
print(f"{flag} carry operation")
"""
1234 123
0 carry operation
1234 765
0 carry operation
1234 876
3 carry operation
1234 766
3 carry operation
1234 666
2 carry operation
1 9999
4 carry operation
1 10000
0 carry operation
0 0
end
"""
자릿수가 다르거나 올림이 다음 자릿수에 영향을 미치는 경우도 포함해 보았습니다.
numlist = []
while True:
n = input("").split(" ")
n = [int(x) for x in n]
if n == [0 , 0] : break
n.sort()
a = [int(x) for x in str(n[0])]
b = [int(x) for x in str(n[1])]
while True:
if len(a) != len(b) : a.insert(0,0)
elif len(a) == len(b) : break
numlist.append([a,b])
for coor in numlist:
count = 0
up = 0
sumindex = len(coor[0]) - 1
while sumindex >= 0 :
sum = up + coor[0][sumindex] + coor[1][sumindex]
if sum >= 10 :
count += 1
up = 1
else : up = 0
sumindex -= 1
if count == 0 : print("No carry operation")
elif count == 1 : print("1 carry operation")
else : print("%d carry operations" %count)
서로 다른자릿수의 숫자를 입력해도 출력되는 코드입니다
def carry_operation(a,b):
c = [int(i) for i in a]
d = [int(i) for i in b]
c.reverse()
d.reverse()
n1 = len(c)
n2 = len(d)
if n1 < n2:
for i in range(0,n2-n1):
c.append(0)
elif n1 > n2:
for i in range(0,n1-n2):
d.append(0)
e= list(zip(c,d))
f= [sum(i) for i in e]
for i in range(len(f)-1):
if f[i]>= 10:
f[i+1] += 1
how_many_carry = 0
for i in f:
if i >= 10:
how_many_carry += 1
else:
break
if how_many_carry == 0:
print("No carry operation")
elif how_many_carry == 1:
print("1 carry operation")
else:
print("%d carry operations"%(how_many_carry))
L = []
while True:
k = input("두 숫자를 입력해라. ex)123 4567>")
L.append(k)
if k == "0 0":
break
for i in L:
if i == "0 0":
break
a,b = i.split(" ")
carry_operation(a,b)
x, y = map(int, input().split())
cnt = 0
carry = False
for i in range(len(str(max(x, y)))+1):
if x%10 + y%10 + carry >= 10:
cnt += 1
carry = True
else:
carry = False
x //= 10
y //= 10
print(cnt)
count=0
x=input('양의 정수 2개를 큰수부터 입력하세요.(큰수 작은수) : ').split()
for i in range(-1, -(len(x[1]) + 1), -1):
if int(x[0][i]) + int(x[1][i])>=10:
count+=1
x[1] = str(int(x[1]) + 10**(-i))
if count<=1:
print('%s carry operation.'%('No' if count==0 else count))
else:
print('%d carry operations.'%count)
data="""123 456
555 555
123 594
0 0"""
lines=data.split('\n')
for line in lines:
[num1,num2]=line.split(' ')
count=0
alpha=0
if int(num1)!=0 or int(num2)!=0:
for i in range(min(len(num1),len(num2))-1,-1,-1):
if alpha:
if int(num1[i])+int(num2[i])+alpha>=10:
count+=1
alpha=1
else:
alpha=0
continue
elif not alpha:
if int(num1[i])+int(num2[i])>=10:
count+=1
alpha=1
else:
alpha=0
continue
print("%d carry opperation"%count)
else: break
def help_children():
cnt = 0
a = int(input())
b = int(input())
carry = 0
for i in range(len(str(max(a,b)))):
if a%10 + b%10 + carry >= 10:
cnt += 1
carry = 1
else:
carry = 0
a = a//10
b = b//10
if cnt == 0:
return 'No carry operation.'
elif cnt == 1:
return '1 carry operation.'
else:
return '{0} carry operations.'.format(cnt)
if __name__ == '__main__':
print(help_children())
a = input("a = ")
b = input("b = ")
count = 0
for i in range(1, min(len(a), len(b))+1):
if int(a[-i]) + int(b[-i]) >= 10:
count += 1
else:pass
print("count =", count)
while True:
carry,result = 0,0
p=list(input("input: ").split())
if p==['0','0']: break
if len(p[0])>=len(p[1]): big,small=p[0],p[1]
else: big,small=p[1],p[0]
for i in range(1,len(big)+1):
if len(small)>=i and int(big[-i])+int(small[-i])+carry>=10:
carry=1
result+=1
elif len(small)<i and int(big[-i])+carry>=10:
carry=1
result+=1
else: carry=0
print(f"{result} carry operation{'s.' if result>1 else '.'}") if result else print("No carry operation.")
짧게 작성하기 실패... 그래도 문제에서 요구한 조건은 전부 만족시켰습니다.
while True:
cnt=0
A, B = input().split(' ')
if A=='0' and B=='0':
break
for i in range(len(A)):
if int(A[i])+int(B[i])>=10:
cnt+=1
if cnt==0:
print('No carry operation')
else:
print('{} carry operations.'.format(cnt))
잘 푼 건가요??
static void primaryArithmetic(int x, int y) {
int carry = 0;
if(x ==0 || y== 0)
return;
for(int i = (x+"").length()-1; i >=0; i--) {
if(((x+"").charAt(i)-48) + ((y+"").charAt(i)-48) >9) {
++carry;
}
}
if(carry == 0)
System.out.println("No carry operation.");
else
System.out.println(carry + " carry operation.");
}
public static void main(String[] args) {
primaryArithmetic(123,456);
primaryArithmetic(555,555);
primaryArithmetic(123,594);
primaryArithmetic(0,0);
}
a = str(input(print('세자리 정수를 입력하세요 : ')))
b = str(input(print('세자리 정수를 입력하세요 : ')))
j = 0
nums = []
a_change = list(map(int, a))
b_change = list(map(int, b))
for i in a_change:
nums.append([i, b_change[j]])
j += 1
check_1 = int((nums[0][0] + nums[0][1]) / 10)
check_2 = int((nums[1][0] + nums[1][1]) / 10)
check_3 = int((nums[2][0] + nums[2][1]) / 10)
sum = check_1 + check_2 + check_3
if (sum == 3):
print('3 carry operation')
if (sum == 2):
print('2 carry operation')
if (sum == 1):
print('1 carry operation')
if (sum == 0) :
print('no carry operation')
public static void carryOperation(int x, int y) {
int count = 0 ;
System.out.println(x);
while (x >= 1 && y >= 1){
if((x%10 + y%10)>=10){
count++;
}
x /= 10; y/=10;
}
if (count==0) System.out.print("No carry operation");
else System.out.println(count+"carry opeartion");
}
input_list = []
num_list = []
carry = 0
sum_carry = 0
while ['0','0'] not in input_list :
input_num = input()
input_list.append(input_num.split())
input_list.remove(['0','0'])
for list1 in input_list:
len_str = len(list1[0]) if len(list1[0]) > len(list1[1]) else len(list1[1])
divnum1 = divmod( int(list1[0]), 10**(len_str-1) )
divnum2 = divmod( int(list1[1]), 10**(len_str-1) )
divnum = divnum1[0] + divnum2[0]
num_list.append(divnum)
for i in range(len_str-2,-1,-1):
divnum1 = divmod( divnum1[1], 10**i )
divnum2 = divmod( divnum2[1], 10**i )
divnum = divnum1[0] + divnum2[0]
num_list.append(divnum)
num_list.reverse()
for i in num_list :
if i+carry >= 10:
sum_carry += 1
carry = 1
else :
carry = 0
if sum_carry == 0 : sum_carry = "No"
print("%s carry operatiion" % sum_carry )
num_list= []
sum_carry = 0
carry = 0
a, b = input("비교하려는 두 숫자를 spece로 분리해서 입력해 주세요.").split()
c = min(len(a),len(b))
judge = lambda x,y: int(x)+int(y)>9
d = [judge(a[-i],b[-i]) for i in range(1,c+1)].count(True)
print(f'{d} carry opertion')
def fun (arr):
m = abs(len(arr[0])-len(arr[1]))
if len(arr[0])>=len(arr[1]):
a = list(reversed(arr[0]))
b = list(reversed(arr[1]))
for i in range(m):
b.append('0')
else:
a = list(reversed(arr[1]))
b = list(reversed(arr[0]))
for i in range(m):
b.append('0')
return a,b
def sol (a,b):
n=0
k=0
for i in range(len(a)):
if int(a[i])+int(b[i])+k >9 :
n+=1
k=1
else:
k=0
return n
arr=[]
while True:
m = input("양의 정수 2개를 입력하시오").split(" ")
if m[0]=='0' and m[1]=='0':
break
else:
if len(m[0])<10 and len(m[1])<10 :
arr.append(m)
for k in arr:
a = fun(k)[0]
b = fun(k)[1]
n = sol(a,b)
if n ==0:
print('No carry operation')
elif n ==1:
print('1 carry operation')
else:
print(n,' carry operations')
1.입력 받은 두 숫자열을 비교해서 열이 적은 숫자열에 0을 추가해서 열수를 맞춰줬습니다. 2.이후 열을 역순 배치후, 각 자리수를 더합니다. 3. 이떄 각 자리수의 합의 9를 넘으면 올림수 발생 횟수인 n을 +1 하고, 자리수 올림 변수 k를 +1 하여 짜봤습니다.
def carry(a):
a = a.split()
count = 0
for i in range(min(len(a[0]),len(a[1]))):
if int(a[0][-i-1]) + int(a[1][-i-1]) >= 10:
count += 1
if count == 0: print("No carry operation.")
elif count == 1: print("1 carry operation.")
else: print(count,"carry operations.")
x = 0
while x == 0:
a = input("Input two numbers (exit:0 0)")
if a == '0 0': x = 1
else: carry(a)
package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;
public class test {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
String a = sc.next();
String b = sc.next();
String[] arr = a.split("");
String[] brr = b.split("");
int carry=0;
for(int i=(a.length()-1); i>=0; i--) {
int sum=0;
int at = Integer.valueOf(arr[i]);
int bt = Integer.valueOf(brr[i]);
sum=at+bt+carry;
if(sum>=10) {
carry+=1;
}
}
if(carry>0) System.out.println(carry + " carry operation");
if(carry==0) System.out.println("No carry operation");
}
}
숫자들을 input으로 입력받게 하였고, 자릿수가 다를 경우도 계산되게끔 하였습니다.
def count(numbers):
num_list= numbers.split(" ")
num1=num_list[0]
num2=num_list[1]
#0을 채워 두 수의 길이를 맞춤.
while len(num1)!=len(num2):
if len(num1)>len(num2):
num2='0'+num2
else:
num1='0'+num1
count=0 #올린 횟수
tenup=0 #올림될 경우 1, 아닐경우 0
for i in range(1,max([len(num1)+1,len(num2)+1])):
sum=0
if int(num1[-i])+int(num2[-i])+tenup<10:
sum+=int(num1[-i])+int(num2[-i])
tenup=0
else:
sum+=int(num1[-i])+int(num2[-i])+tenup-10
count+=1
tenup=1
return count
nums=''
resert=[]
while nums != '0 0':#0 0이 입력될 때 까지 계속 입력
nums=input()
if nums !='0 0': #0 0인 경우 출력x
pass
if count!=0:
resert.append('%d carry operation.'%count(nums))
else:
resert.append('No carry operation.')
else:
pass
print('\n'.join(resert))
3자리와 0만 생각해서 만들었습니다..
def m(n1,n2):
n1s = [int(a) for a in str(n1)]
n2s = [int(a) for a in str(n2)]
i = -1
cstack = 0
while i>=-4:
if i == -4:
if cstack > 0: return print("%d carry operation." %cstack)
else: return print("No carry operation.")
if n1==0 and n2==0: break
if n1s[i]+n2s[i]>=10:
cstack += 1
if i>=-2: n1s[i-1]+1
elif i<=-3: pass
i -= 1
elif n1s[i]+n2s[i]<10: i -= 1
elif i == -3:
if cstack > 0: return print("%d carry operation." %cstack)
else: return print("No carry operation.")
def primaryArithmatic():
print("각 라인당 양의 정수를 두개씩 입력하되, 마지막 라인은 0 0을 입력한다.")
# 입력할 변수들의 빈리스트
firstNum = []
secondNum = []
while True:
# 각각 양의 정수 입력
a, b = input().split()
# 0 0 입력 될 경우 입력 종료
if int(a) == 0 and int(b) == 0:
break
else:
# 입력된 값을 추가하여 리스트화
firstNum.append(a)
secondNum.append(b)
# 각 리스트에서 요소를 추출
for numA, numB in zip(firstNum, secondNum):
count = 0 # 한자리 올림 수 초기화
over = 0 # 올림이 있을 경우 다음 자리수에 합산 할 값 초기화
# 요소를 뒤집어서 뒷자리부터 추출
for digitA, digitB in zip(numA[::-1], numB[::-1]):
# 각 자리 숫자의 합산과 올림 수 합산이 10을 넘을 경우 올림 수(count) 증가, 다음 자리 수 합산 값(over)에 1 저장
if ((int(digitA) + over) + int(digitB)) >= 10:
count += 1
over = 1
# 올림 수가 없는 경우 'No' 저장
if count == 0:
count = 'No'
print(f"{count} carry operation")
def carry(a,b):
_count = 0
_q = 1000
while a % _q > 0 and b % _q > 0:
if a % _q + b % _q >= _q :
_count += 1
_q = _q / 10
if _count >1:
return str(_count) + " carry operations."
elif _count == 1:
return "1 carry operation."
else:
return "No carry operation."
while과 if문만 가지고 열심히 만들어보았습니다. 많이 배웁니다. 감사합니다.
two_number = input()
two_number_list = two_number.split(" ")
x = two_number_list[0]
y = two_number_list[1]
sum = int(x)+int(y)
z = str(sum)
ca_op = 0
if len(y)<=len(x):
for i in range(len(y)):
if int(z[-i])<int(x[-i])+int(y[-i]):
ca_op += 1
for j in range(len(y),len(x)):
if int(z[-j])<int(x[-j]):
ca_op += 1
elif len(y)>len(x):
for i in range(len(x)):
if int(z[-i])<int(x[-i])+int(y[-i]):
ca_op += 1
for j in range(len(x),len(y)):
if int(z[-j])<int(y[-j]):
ca_op += 1
if ca_op == 0:
print("No carry operation")
elif ca_op == 1:
print("1 carry operation")
else:
print("%d carry operations." %ca_op)
def carry(a,b):
al = [int(i) for i in str(a)]
bl = [int(i) for i in str(b)]
abl = list(zip(al,bl))
count = 0
for i in abl:
if sum(i) >= 10:
count += 1
if count == 0:
return 'No carry operation.'
elif count == 1:
return '1 carry operation.'
else:
return f'{count} carry operations'
자바로 풀어봤습니다.
import java.util.Scanner;
import java.util.ArrayList;
public class programming {
public static int arithmetic(String inputData) {
// 초기화
int result=0;
String[] numberString = inputData.split(" ");
int[] number = new int[2];
for(int i=0; i<2; i++)
number[i] = Integer.parseInt(numberString[i]);
// 최대 숫자 길이 판단
int max = 0;
if(numberString[0].length()>numberString[1].length())
max = numberString[0].length();
else
max = numberString[1].length();
// 한자리올림 판단
int perviousRounding = 0;
while(max>0) {
int sum = perviousRounding;
for(int i=0; i<2; i++)
sum += (number[i]%10);
if(sum>=10) {
result++;
perviousRounding = 1;
}else
perviousRounding = 0;
for(int i=0; i<2; i++)
number[i] = (number[i]/10);
max--;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> storage = new ArrayList<>();
// 입력
while(true) {
System.out.print("양의 정수들 두 개 입력:");
int x = scan.nextInt();
int y = scan.nextInt();
if(x==0 & y==0) {
break;
}else {
String numberString = String.valueOf(x)+" "+String.valueOf(y);
storage.add(numberString);
}
}
// 올림 연산
int[] result = new int[storage.size()];
for(int i=0; i<storage.size(); i++)
result[i] = arithmetic(storage.get(i));
// 결과 출력
for(int i=0; i<storage.size(); i++) {
if(result[i]==0)
System.out.println("No carry operation.");
else
System.out.printf("%d carry operation.\n", result[i]);
}
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class PrimaryArithmetic {
public static void main(String[] args) {
int fCount = 0, sCount = 0;
List<Integer> firstN = new ArrayList<>();
List<Integer> secondN = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.println("형식에 맞춰 입력해 주세요:");
while (true) {
String input = sc.nextLine();
try {
if (!input.equals("0 0")) {
String[] temp = input.split(" "); // 공백으로 구분해서 비교할 1열 2열 리스트에 각각 값 추가
firstN.add(fCount, Integer.parseInt(temp[0]));
secondN.add(sCount, Integer.parseInt(temp[1]));
System.out.print(firstN.get(fCount));
System.out.println(" " + secondN.get(sCount));
fCount++;
sCount++;
} else {
break;
}
} catch (NumberFormatException e) {
System.out.println("정수만 입력해 주세요.");
}
}
System.out.println("계산 시작");
List<Integer> finResult = magicBox(firstN, secondN);
System.out.println("결과 출력: ");
if (finResult.size() > 1) {
for (Integer i : finResult) {
System.out.printf("%d행 -> 한자리 올림 %d회 시행\n", finResult.indexOf(i)+1, i);
}
} else {
System.out.printf("한자리 올림 %d회 시행\n", finResult.get(0));
}
}
public static List<Integer> magicBox(List<Integer> a, List<Integer> b) {
List<Integer> resultList = new ArrayList<>();
for (int i = 0; i < a.size(); i++) {
String aStr = String.valueOf(a.get(i)); //리스트 인덱스 1을 거꾸로된 숫자 배열로 만들기
String[] aStrDiv = aStr.split("");
String bStr = String.valueOf(b.get(i));
String[] bStrDiv = bStr.split("");
List<Integer> ailist = new ArrayList<>();
List<Integer> bilist = new ArrayList<>();
for (String s : aStrDiv) {
ailist.add(Integer.parseInt(s));
Collections.reverse(ailist);
}
for (String s : bStrDiv) {
bilist.add(Integer.parseInt(s));
Collections.reverse(bilist);
}
int counter = 0;
int upped = 0;
int aIdx = 0;
int bIdx = 0;
while (true) { // 낮은 자리부터 a와 b의 각 숫자 더해서 카운터 쌓기
int temp = ailist.get(aIdx) + bilist.get(bIdx) + upped;
if (temp > 9) {
counter++;
aIdx++;
bIdx++;
upped = 1;
} else {
aIdx++;
bIdx++;
upped = 0;
}
if (aIdx == ailist.size() || bIdx == bilist.size()) {
resultList.add(i, counter);
break;
}
}
System.out.println("계산중: " + (i+1) +"번째 행");
}
return resultList;
}
}
nums = []
n = 0
while True:
if n >= 10:
exit('Error : > 10')
else:
n += 1
data = input().split()
if data == ['0', '0']:
break
else:
nums.append(data)
for i in nums:
ans = 0
for j in range(len(i[0])):
if int(i[0][j])+int(i[1][j]) > 9:
ans +=1
if ans == 0:
print('No carry operation.')
else:
print(ans, 'carry operation.')
Python 3.11 버전입니다 첫 번째 풀이는 일의 자리부터 쭉 조사하면서 확인하는 함수인데, 하다보니 그냥 두 수를 더한 결과값으로만 비교를 할 수 있지 않을까 해서 한 개 더 짜봤는데 이건 각 자리의 수를 더한다는 게 다른 자리 수에 영향을 받아서 결국 순차적으로 올림을 하는 함수를 도입해야 올바른 출력값을 도출할 수 있네요. 두 번째는 모든 자리가 올림이 되어야만 잘 출력되고 그 외에는 잘못 출력됩니다. 오류난 함수도 한 번 올려봤어요
a = input()
def Primary_Arithmetic(n):
n = n.split()
L = max(len(n[0]),len(n[1]))
for i in range(0,2):
n[i] = "{0:0>{1}}".format(n[i],L)
x = 0
n0 = list(x for x in n[0])
n1 = list(x for x in n[1])
for k in range(-1,-L-1,-1):
if k>=-L+1:
if int(n0[k])+int(n1[k]) > 9:
x+=1
n0[k-1] = str(int(n0[k-1])+1)
else:
if int(n0[k])+int(n1[k]) > 9:
x+=1
print("%d carry operation" % x)
def Primary_Arithmetic2(n):
n = n.split()
L = max(len(n[0]),len(n[1]))
N = str(int(n[0])+int(n[1]))
for i in range(0,2):
n[i] = "{0:0>{1}}".format(n[i],L)
x = 0
for k in range(-1,-L-1,-1):
if int(n[0][k])+int(n[1][k]) != int(N[k]):
x +=1
print("%d carry operation" % x)
Primary_Arithmetic(a)
Primary_Arithmetic2(a)
L4=[];
while True:
L1=[]; L2=[]; L3=[]; c=0
a, b=map(int, input().split())
if a==0 and b==0:
break
for i in range(len(str(a))):
L1.append(a%10)
a//=10
for i in range(len(str(b))):
L2.append(b%10)
b//=10
L3.append(len(L1)); L3.append(len(L2))
for i in range(min(L3)):
if L1[i]+L2[i]>=10:
c+=1
if i+1 == min(L3):
break
if L3.index(min(L3))==0:
L1[i+1]+=1
else:
L2[i+1]+=1
L4.append(c)
for i in range(len(L4)):
if L4[i] != 0:
print('%d carry operations.' %L4[i])
else:
print('No carry operation.')
while True:
# 입력 받기
a, b = input().split()
# 종료 조건
if a == '0' and b == '0':
break
# 입력 받은 두 수의 자리수를 맞추기 위해 더 짧은 수의 앞 부분을 0으로 채운다.
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
# 덧셈을 수행하면서 한자리올림이 발생하는 횟수를 계산한다.
carry = 0
carry_count = 0
for i in range(max_len - 1, -1, -1):
carry = (int(a[i]) + int(b[i]) + carry) // 10
if carry == 1:
carry_count += 1
# 결과 출력
if carry_count == 0:
print("No carry operation.")
elif carry_count == 1:
print("1 carry operation.")
else:
print("{} carry operations.".format(carry_count))
혼자 푼 건 아니고 ChatGPT의 도움을 좀 받았습니다. 그래도 기본적인 거 물어보는 거 말고는 제가 풀었습니다. 자릿수가 달라도 잘 작동하네요. 포멧은 출제자 의도와는 좀 다릅니다만.
인공지능에게 요청했더니 한줄 코드로도 만들어 주는데 가독성이 극악이라서 실용성은 제로인 것 같네요. 그래도 다른 분들 참고 하시라고 남겨둡니다.
print("No carry operation." if all(i == '0' for i in (a, b)) else f"{sum(int(ai) + int(bi) > 9 for ai, bi in zip(a.zfill(max(len(a), len(b))), b.zfill(max(len(a), len(b)))))} carry {'operation' if sum(int(ai) + int(bi) > 9 for ai, bi in zip(a.zfill(max(len(a), len(b))), b.zfill(max(len(a), len(b))))) == 1 else 'operations'}.")
def primary(): a, b = input().split() s, t = int(a), int(b)
if s < t:
a, b = b ,a
c_cnt = 0
if len(a) == len(b):
for i in range(len(a) - 1, -1, -1):
carry = halfadder(a[i], b[i])
if carry != 0:
c_cnt += 1
else:
cha = len(a) - len(b) - 1
for i in range(len(b) - 1, -1, -1):
carry = halfadder(a[i], b[i])
if carry != 0:
c_cnt += 1
if i == 0:
f_carry = carry
if f_carry == 1:
for j in range(cha, -1, -1):
carry = halfadder(a[j], f_carry)
if carry != 0:
c_cnt += 1
f_carry = carry
else:
break
print(c_cnt)
primary()
def GetCarrierCount (number1, number2):
list1 = list(str(number1))[::-1]
list2 = list(str(number2))[::-1]
diff = len(list1) - len(list2)
if diff > 0:
for i in range(diff):
list2.append('0')
elif diff < 0:
for i in range(diff * -1):
list1.append('0')
CarryOverCount = 0
CarryOverFlag = 0
for a, b in zip(list1, list2):
if int(a) + int(b) + CarryOverFlag >= 10:
CarryOverCount = CarryOverCount + 1
CarryOverFlag = 1
else:
CarryOverFlag = 0
return CarryOverCount
print("123 + 456 = 579 : Carry operation %d" % GetCarrierCount(123,456))
print("555 + 555 = 1110 : Carry operation %d" % GetCarrierCount(555, 555))
print("123 + 594 = 717 : Carry operation %d" % GetCarrierCount(123,594))
print("1 + 99999 = 100000 : Carry operation %d" % GetCarrierCount(1, 99999))
fst_list = [];snd_list = [];output_list = []
fst = 0;snd = 0;carry = 0
while True:
fst,snd = input("Numbers:").split()
if int(fst) == 0 and int(snd) == 0:break
else:
for i in reversed(fst): fst_list.append(int(i))
for j in reversed(snd): snd_list.append(int(j))
for pair in zip(fst_list,snd_list):
_sum = sum(pair)
if _sum >= 10 : carry += 1
else: continue
output_list.append(carry)
for i in output_list:
if i == 1 or i == 0 : print(i,"Carry operation.")
else: print(i,"Carry operations.")
def add_nums(num1, num2):
up = 0
op = 0
while num1 > 0 or num2 > 0:
up = (num1%10 + num2%10 + up)//10
num1, num2 = num1//10, num2//10
op += up
return op
num1, num2 = map(int, input('>>>').split())
ans = add_nums(num1, num2)
if ans == 0:
print('No carry operation.')
else:
print('%d carry operation.' %(ans))
list_output=list()
while True:
list_operation_number_1=[0 for a in range(10)]
list_operation_number_2=[0 for a in range(10)]
print(list_operation_number_1)
print(list_operation_number_2)
number_1,number_2=input().split()
if number_1=='0' and number_2=='0':
break
print(number_1,number_2)
list_number_1=list(map(int,list(number_1)))
list_number_2=list(map(int,list(number_2)))
print(list_number_1,list_number_2)
a=(len(list_operation_number_1)-1)
for b in range((len(list_number_1)-1),-1,-1):
list_operation_number_1[a]=list_number_1[b]
a-=1
print(list_operation_number_1)
a=(len(list_operation_number_2)-1)
for b in range((len(list_number_2)-1),-1,-1):
list_operation_number_2[a]=list_number_2[b]
a-=1
print(list_operation_number_2)
carry_count=0
for a in range(9,-1,-1):
if 10<=(list_operation_number_1[a]+list_operation_number_2[a]):
carry_count+=1
if a!=0:
list_operation_number_1[a-1]+=1
print(carry_count)
if carry_count==0:
list_output.append("No carry operation.")
elif carry_count==1:
list_output.append("{} carry operation.".format(carry_count))
else:
list_output.append("{} carry operations.".format(carry_count))
for a in list_output:
print(a)
JAVA입니다.
package primary_arithmetic;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Carry {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
List<List<String>> numbers = new ArrayList<List<String>>();
String input = "";
while(true) {
input = sc.nextLine();
if(input.equals("0 0")) {
break;
}
else {
List<String> inputs = new ArrayList<String>();
inputs.add(input.split(" ")[0]);
inputs.add(input.split(" ")[1]);
numbers.add(inputs);
}
}
sc.close();
for (List<String> list : numbers) {
int carryCount = carry(list.get(0), list.get(1));
switch (carryCount) {
case 0:
System.out.println("No carry operation.");
break;
case 1:
System.out.println("1 carry operation.");
break;
default:
System.out.println(carryCount + " carry operations.");
break;
}
}
}
public static int carry(String str1, String str2) {
StringBuffer sb1 = new StringBuffer();
sb1.append(str1);
sb1.reverse();
char[] chars1 = sb1.toString().toCharArray();
StringBuffer sb2 = new StringBuffer();
sb2.append(str2);
sb2.reverse();
char[] chars2 = sb2.toString().toCharArray();
int minLength = Math.min(chars1.length, chars2.length);
int count = 0;
int carry = 0;
for (int i = 0; i < minLength; i++) {
if(carry + Character.getNumericValue(chars1[i]) +
Character.getNumericValue(chars2[i]) >= 10) {
count += 1;
carry = 1;
}
else {
carry = 0;
}
}
return count;
}
}
def counting_plus_counting():
while True:
a, b = map(int, input().split())
if a == 0 and b == 0:
break
count = 0
str_a = str(a)[::-1]
str_b = str(b)[::-1]
carry = 0
for i in range(max(len(str_a), len(str_b))):
digit_a = int(str_a[i]) if i < len(str_a) else 0
digit_b = int(str_b[i]) if i < len(str_b) else 0
if digit_a + digit_b + carry >= 10:
count += 1
carry = 1
else:
carry = 0
print(str('No' if count == 0 else count) + ' carry operations.')
counting_plus_counting()