Input an integer containing only 0s and 1s (i.e., a “binary” integer) and print its decimal equivalent.
[Hint: Use the remainder and division operators to pick off the “binary” number’s digits one at a time from right to left. Just as in the decimal number system, in which the rightmost digit has a positional value of 1, and the next digit left has a positional value of 10, then 100, then 1000, and so on, in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, and so on. Thus the decimal number 234 can be interpreted as4 * 1 + 3 * 10 + 2 * 100 . The decimal equivalent of binary 1101= 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 ]
Input Specification:Input an integer containing only 0s and 1s.
Output Specification:Print its decimal equivalent of binary (1101 = 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 ). After showing the number, seperate each number and symbol by ong space.
Sample Input:1001101Sample Output:
1001101 = 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 + 0 * 16 + 0 * 32 + 1 * 64
结尾无空行
作者sunjun单位武汉理工大学代码长度限制16 KB时间限制400 ms内存限制64 MB
答案:
#include
#include
#include
#include
using namespace std;
int main(){
char str[10];
cin >> str;
char cha[10] = {0};
strcpy(cha,str);
string str2 = " * ";
string str3 = " + ";
string str1[10];
for(int i=strlen(str)-1,j=0; i>=0,j<=strlen(str)-1; i--,j++){
if(j != strlen(str)-1){
str1[j] += cha[i];
str1[j] += str2;
str1[j] += std::to_string((int)pow(2,j));
str1[j] += str3;
}else{
str1[j] += cha[i];
str1[j] += str2;
str1[j] += std::to_string((int)pow(2,j));
}
}
cout << str << " = ";
for(int i=0; i<=strlen(str); i++)
cout << str1[i];
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)