Value conversion issues (two) adjacent digital base ranging ratio: the number of skew

Numeric conversion problem (ii)

Neighbors are unequal base ratio: the number of skew

In skew binary representation, the value of k bits xk represents xk × (2 ^ (k + 1) -1). The numbers above each bit may be 0 or 1, the final surface 2 may be a non-zero bit, e.g., 10120 (skew) = 1 × (2 ^ 5-1) + 0 × (2 ^ 4-1) + 1 × (2 ^ 3-1) + 2 × (2 ^ 2-1) + 0 × (2 ^ 1-1) = 31 + 0 + 7 + 6 + 0 = 44. The first ten skew number is 0 , 2,10,0 = 44. skew is 0,1,2,10 before ten numbers,
11,12,20,100,101, and 102.
Input data
input comprising one or more rows, each row contains an integer n. If n = 0 indicates the end of input, skew or n is a number of
output requirements
for each of the input and output of its decimal representation. Converted to decimal, n is not more than 231-1 = 2147483647

Code
#include <stdio.h>
#include <string.h>
int main(){
int i,k,base[31],sum;
char skew[32];
base[0]=1;
for(i=1;i<31;i++)
base[i]=2*base[i-1]+1; // base[i]=2^(i+1)-1=2 *( 2 ^ i -1)+1=2 * b[i-1]+1
while(1){
scanf("%s",skew);
if(strcmp(skew,“0”)==0)
break;
sum=0;
k=strlen(skew);
for(i=0;i<strlen(skew);i++){
k–;
sum+=(skew[i]-‘0’)*base[k];
}
printf("%d\n",sum);
}
return 0;
}
Topic analysis
(1) adjacent bit of skew, no geometric relationship between the base. After each calculation of a base, then converted to decimal. The length of skew k is a number, the last digit of the radix-2 ^ (k-1). Since converted to decimal, not more than n-2 ^ (31-1), the input number is the maximum length of not more than 31 skew.
(2) by an integer array base [31], the number of skew sequentially stores the last bit, the penultimate 2, ......, 31 of the base value. Using this array, skew converts each number to the corresponding decimal number.

to sum up
(1) The last bit is 0, i.e., k = 0. Therefore, according to the number of time into the reciprocal of Equation 5 is actually the sixth.
(2) ** strcmp: ** function compares two strings, the two strings is provided str1, str2,
if str1 == str2, it returns zero;
if str1 <str2, returns a negative number;
if str1> str2 , a positive number is returned.
(3) base [i] = 2 ^ (i + 1) -1 = 2 * (2 ^ i -1) + 1 = 2 * b [i-1] +1
through base [k] calculated value, identify base [i] relationship base [i-1] and, identify the relationship mathematically.
But substituting 2 ^ (i + 1) -1 is calculated directly result of the error, I do not know why.

Guess you like

Origin blog.csdn.net/m0_45128748/article/details/91350431