balanced ternary notation
来源:互联网 发布:2017洗车软件app 编辑:程序博客网 时间:2024/06/01 08:58
"Perhaps the prettiest number system of all... is the balanced ternary notation."——Donald Knuth
平衡三进制(balanced ternary notation),是一种以3为基数,-1(以下用T表示)、0、1为基本数码的进制。
例题:砝码问题
解法1:
枚举
#include <iostream>using namespace std;int main(){ /* *-1,0,1 represent 3 status */ int testNum=7; int w1=1; int w2=3; int w3=9; int w4=27; int w5=81; for (int i=-1; i<=1; i++) { for (int j=-1; j<=1; j++) { for (int k=-1; k<=1; k++) { for (int m=-1; m<=1; m++) { for (int n=-1; n<=1; n++) { int tmp=w1*i+w2*j+w3*k+w4*m+w5*n; if (tmp==testNum) { cout<<w5<<" "<<n<<endl; cout<<w4<<" "<<m<<endl; cout<<w3<<" "<<k<<endl; cout<<w2<<" "<<j<<endl; cout<<w1<<" "<<i<<endl; } } } } } } return 0;}
解法2:
使用平衡三进制
#include <iostream>using namespace std;int main(){ cout<<"pls input one number between 1 and 121"<<endl; int input_Number; cin>>input_Number; if (input_Number<0||input_Number>121) { cout<<"pls input the right number between 1 and 121"<<endl; return 0; } char sign[10]; int temp[10]={0}; int tem=1; int len=0; int remainder=0; int quotient=1; while (quotient!=0) { quotient=input_Number/3; remainder=input_Number%3; if (remainder==2) { input_Number=quotient+1; temp[len]=tem; sign[len++]='-'; } if(remainder==1){ input_Number=quotient; temp[len]=tem; sign[len++]='+'; } if (remainder==0) { input_Number=quotient; } tem=tem*3; } cout<<temp[len-1]; for (int i=len-2; i>=0; i--) { cout<<sign[i]<<temp[i]; } cout<<endl; return 0;}
输出所有情况
#include <iostream>using namespace std;int main(){ int len=0,a[10]={0},j;char op[10];int t,k,m,input,i;for(j=1;j<=122;j++){ input=j; m=j; len=0; t=1; while(input) { k=input%3; input/=3;//关键是这里的两步 switch(k) { case 0:break; case 1:a[len]=t;op[len++]='+';break; case 2:a[len]=t;op[len++]='-';input++;break; } t*=3; } printf("%d=%d",m,a[len-1]); for(i=len-2;i>=0;i--) printf("%c%d",op[i],a[i]); printf("\n");} return 0;}
参考:
平衡三进制
0 0
- balanced ternary notation
- Ternary Password
- Ternary Calculation
- Ternary Password
- Ternary Expression
- Ternary Tree
- Ternary Calculation
- (.NET) Ternary控件: TGas
- Uva 11185 - Ternary
- B. Ternary Logic
- UVa 11185 - Ternary
- ZOJ Ternary Calculation
- G、Ternary Calculation
- ZOJ3782:Ternary Calculation
- zoj3782 Ternary Calculation
- ZOJ 3782 Ternary Calculation
- ZOJ 3782 Ternary Calculation
- G.Ternary Calculation
- 编码详解
- C语言与JAVA语言中基本数据类型长度的比较
- 企业O2O网络营销的10大原则
- 凸包
- Python编写检测数据库SA用户的方法
- balanced ternary notation
- RabbitMQ工作队列之Python实现
- shell排序
- Python & 数据分析学习笔记[第1篇]
- 线段树入门(1)
- LR中,URL -based script与HTML -based script区别
- jQuery 事件方法
- -[算法导论]Dynamic Programming总结(没完成)
- 线段树入门(2)区间插入求和