B - Ternary Logic

B - Ternary Logic
Little Petya very much likes computers. Recently he has received a new “Ternatron IV” as a gift from his mother. Unlike other modern computers, “Ternatron IV” operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it).

It turned out that the operation does exist (however, it is called tor) and it works like this. Suppose that we need to calculate the value of the expression a tor b. Both numbers a and b are written in the ternary notation one under the other one ( b under a). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren’t transferred). For example: 1410 tor 5010 = 01123 tor 12123 = 10213 = 3410.

Petya wrote numbers a and c on a piece of paper. Help him find such number b, that a tor b = c. If there are several such numbers, print the smallest one.

Input
The first line contains two integers a and c (0 ≤ a, c ≤ 109). Both numbers are written in decimal notation.

Output
Print the single integer b, such that a tor b = c. If there are several possible numbers b, print the smallest one. You should print the number in decimal notation.

Examples

Input
14 34
Output
50

Input
50 34
Output
14

Input
387420489 225159023
Output
1000000001

Input
5 5
Output
0

题意 :对于c的三进制的每一位由a与b的三进制对应位加和%3得出,知道a,c求最小的b
直接求出a,c的三进制,根据题目规则求出b的三进制,最后把b转化成10进制就是结果

#include<iostream>
#include<cmath>
using namespace std;
int a, b, c, i, j, k, sa[100], sb[100], sc[100], l1, l2, l;
int main()
{
	l1 = l2  = 0;
	cin >> a >> c;
	while (a) {
		sa[l1] = a % 3;
		l1++;
		a /= 3;
	}
	if (l1 > 0) l1--;//sa[l1]==0,我们要找到不为0的那一位,a==0的话不处理
	while (c) {
		sc[l2] = c % 3;
		l2++;
		c /= 3;
	}
	if (l2 > 0) l2--;
	l = (l1 > l2) ? l1 : l2;
	for (i = 0; i <= l; i++)
	{
		while ((sa[i] + sb[i]) % 3 != sc[i]) sb[i]++;//因为每一位只有0,1,2,所以直接暴力了,并且确定的值一定是最小的
	}
	for (i = 0; i <= l; i++)
	{
		b +=((long long) pow(3, i) )* sb[i];//pow()返回值为double型,做一下类型转换
	}
	cout << b;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值