UVA763 LA5339 Fibinary Numbers大数
Posted 海岛Blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA763 LA5339 Fibinary Numbers大数相关的知识,希望对你有一定的参考价值。
The standard interpretation of the binary number 1010 is 8 + 2 = 10. An alternate way to view the sequence “1010” is to use Fibonacci numbers as bases instead of powers of two. For this problem, the terms of the Fibonacci sequence are:
1
,
2
,
3
,
5
,
8
,
13
,
21
,
.
.
.
1, 2, 3, 5, 8, 13, 21, . . .
1,2,3,5,8,13,21,...
Where each term is the sum of the two preceding terms (note that there is only one 1 in the sequence as defined here). Using this scheme, the sequence “1010” could be interpreted as 1·5+0·3+1·2+0·1 = 7. This representation is called a Fibinary number.
Note that there is not always a unique Fibinary representation of every number. For example the number 10 could be represented as either 8 + 2 (10010) or as 5 + 3 + 2 (1110). To make the Fibinary representations unique, larger Fibonacci terms must always be used whenever possible (i.e. disallow 2 adjacent 1’s). Applying this rule to the number 10, means that 10 would be represented as 8+2 (10010).
Write a program that takes two valid Fibinary numbers and prints the sum in Fibinary form.
Input
The input file contains several test cases with a blank line between two consecutive.
Each test case consists in two lines with Fibinary numbers. These numbers will have at most 100 digits.
Output
For each test case, print the sum of the two input numbers in Fibinary form.
It must be a blank line between two consecutive outputs.
Sample Input
10010
1
10000
1000
10000
10000
Sample Output
10100
100000
100100
问题链接:UVA763 LA5339 Fibinary Numbers
问题简述:(略)
问题分析:大数问题,用Java来解决。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的Java语言程序如下:
/* UVA763 LA5339 Fibinary Numbers */
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
static BigInteger getd(String a, BigInteger fib[]) {
BigInteger ret = BigInteger.ZERO;
for(int i = 0; i < a.length(); i++)
if(a.charAt(i) == '1')
ret = ret.add(fib[a.length() - 1 - i]);
return ret;
}
public static void main(String args[]){
int N = 200;
Scanner input = new Scanner(System.in);
BigInteger fib[] = new BigInteger[200];
fib[0]=BigInteger.ONE;
fib[1]=BigInteger.valueOf(2);
for (int i = 2; i < N; i++)
fib[i] = fib[i - 1].add(fib[i - 2]);
int flag = 0;
while(input.hasNext()) {
if (flag == 1) System.out.println("");
flag = 1;
BigInteger ans = BigInteger.ZERO;
String a = input.next();
ans = getd(a, fib);
a = input.next();
ans = ans.add(getd(a, fib));
int flag2 = 0;
for(int i = N - 1; i >= 0; i--) {
if(ans.compareTo(fib[i]) >= 0) {
flag2 = 1;
System.out.print("1");
ans = ans.subtract(fib[i]);
}
else if(flag2 == 1) System.out.print("0");
}
if(flag2 == 0) System.out.print("0");
System.out.println();
}
}
}
以上是关于UVA763 LA5339 Fibinary Numbers大数的主要内容,如果未能解决你的问题,请参考以下文章
UVA1482 LA5059 Playing With StonesSG函数