Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to write a function that identifies the leading digit of a integer number.I am confused and in lack of knowledge to write a function for this process.Can someone help me?
The simple, and naive, solution is to convert the number to a string, and get the first character of the string and convert it back into a number.
Another solution is to divide by ten in a loop, until the result is zero, while remembering the last digit of the number. When the result is zero, the last digit is the first digit of the whole number.
This can be done easily in two steps.
Change the number to string.
Return the first char of the string.
int num = 12345;
// left most digit:
int digit = abs(num);
while (digit > 9) {
digit /= 10;
}
// right most digit:
int digit = abs(num) % 10;
If you feel more confortable by using arithmetic instead strings and loops, try this approach:
Calculate the integer part of the base 10 logarithm
Divide the source number by 10 power to the integer part of the log
{
int value = abs(978);
int valuelog = (int)log10(value);
int leadingDigit = value / (pow(10,valuelog));
printf("%d", leadingDigit);
}
Example 978:
log10(978)->2.990; int 2
pow(10, 2)->100
978/100->9.78; int 9
#include <stdio.h>
int lead(const int number) {
int divider = 10;
while (number/divider) {
divider *= 10;
}
return number/(divider/10);
}
main()
{
int number = 678;
int leadNumber = lead(number);
printf("%d",leadNumber);
}
you can do that by converting the integer to string and return the first character.
or you can do a simple program as below.
int a;
scanf("%d",&a);
while(a/10>0)
{
a=a/10
}
printf("leading no. of given input is %d\n",a);
int lead_int(const int n) {
return (abs(n) < 10) ? abs(n) : lead_int(n /10);
}
Edited after seeing comments in this post (to include abs()), And made this a one lined function.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to create a function to take a string like this "2014-02-13T06:20:00"
and to convert to a long long int like 20140213062000.
Has anyone a idea how this can be done?
Here is an algorithm, you will just write the code:
define a long long variable n and initialize it to 0.
for each character c in the string:
if c is a digit, ie greater or equal to '0' and less or equal to '9':
multiply n by 10 and add the value represented by c, store the result in n.
else:
ignore the non digit character
n should have the expected value.
This would convert positive values. If the string has an initial - indicating a negative number, you would test that and negate the number at the end. Note also that overflowing the range of long long int has undefined behavior with this approach.
Your attempt in the comment needs some improvements:
long long string_To_long(const char sl[]) {
long long int n = 0;
for (int i = 0; sl[i] != '\0'; i++) {
char c = sl[i];
if (c >= '0' && c <= '9')
n = n * 10 + (c - '0');
}
return n;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Good night, what's the best way in C to count the number of possibilities of UNIQUE anagrams in a string with the maximum length of 256 without allows repetitions caused by same letters? The input would be just in uppercase and only alphabet letters are allowed, A-Z. I got stuck in the worst case of the program that got 26! a very large number that overflow even my double. I think I'm very lost here, I'm not so good in C. The program just need to shows the number of possibilities, not the anagram. Like:
LOL = 3
HOUSE = 120
OLD = 6
ABCDEFGHIJKLMNOPQRSTUVWXYZ = 403291461126605635584000000
Thank you guys very much... I tried a lot and failed in every single tried, I'm in distress with it. The way I got more closer of do it was in Pascal, but it also failed in some tests, and I can't use Pascal anyway. I'm using CodeBlocks on Windows that compiles with GCC.
You should calculate factorial of the length of the given string divided by the factorial of the occurrence of every letter.
long double logFactorial (int i) {
return i < 2 ? 0.L : (logFactorial (i-1)+log(long double (i));
}
int countLetter(const char* str, char c) {
int res = 0;
while (str && *str) {
res += *str++ == c;
}
return res;
}
long double numPermutations(const char* str) {
auto res = logFactorial (strlen(str));
for (char c = 'A'; c<='Z'; c++) {
res -= logFactorial (countLetter (str,c));
}
return exp((long double)res);
}
Pay attention!
There are several people here who were correct by saying that factorial of 26 cannot be stored even in 64bit integer.
Therefore, I changed my calculation to the logarithmic of the factorial number and store it in long double which I hope is precise enough (I think that the exp() function is not precise enough)
Nevertheless you cannot use this result as an integer value, unless you find a way to store it in 128bit integer or bigger...
You should test it too if this fits your problem.
There is a faster way to calculate the factorial for this problem by storing the results of 0! up to 26! in an array of the size of [27].
I will leave it to you for asking another question.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
int main(){
int x;
int sum;
printf("Enter a positive integer: ");
scanf("%d", &x);
do{
sum += (x%10);
x=(x/10);
if((x/10)==0){
sum += x;
}
}
while((x/10)!=0);
printf("%d",sum);
}
Hey, I'm trying to get this to add up each digit within the entered integer, but the code I'm using keeps returning the wrong output. Would someone please help me fix my equation/code, because I'm not sure why the output is incorrect.
in your code
int sum;
is not initialized. use something like
int sum = 0;
Note: local variables are not automatically initialized [to 0 or anything], without explicit initialization their contents will be garbage. Thereby, using sum += (x%10); will lead to read before-write scenario, producing wrong result.
Here is a small math problem:
Somebody gave you ten apples, then someone else gave you two more. How many apples do you have?
The right answer is that this question is impossible to answer, because nobody told you how many apples you had at the beginning.
Your program suffers from the same problem: you failed to initialize sum before starting to add to it, so it has initial "garbage" value.
Changing the declaration to
int sum = 0;
will fix the problem.
Initialize your variable sum -
int sum = 0;
If you don't initialize your variable in C and some other language then the a garbage/random value is assigned to it when it is used in expression for the first time.
Late Answer
Since you've already found the problem with your code, I would like to provide a more concise alternative:
int x;
int sum = 0
int digit;
printf("Enter a positive integer: ");
scanf("%d", &x);
while (x > 0) {
digit = x % 10;
sum += digit;
x /= 10;
}
printf("%d", sum);
x % 10 extracts the last digit of the number, and then x /= 10 truncates the integer by removing the last digit.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The program is suppose to convert binary number to decimal form. Only using scanf() and printf() library functions. Takes in a char array from user ---no prompt outputs decimal form, function must be used with parameter (char binaryString[]) after conversion result must be printed out in main. Program does not work don't think I'm converting the binary form to decimal form correctly in function binaryToDecimal since i cant use pow() I'm lost
#include <stdio.h>
#include <math.h>
int binaryToDecimal(char binaryString[]) {
int c, j = 1, decimalNumber = 0;
for (binaryString[c = 0]; binaryString[c] > binaryString[33];
binaryString[++c]) {
while (binaryString[c] != 0) {
remainder = binaryString[c] % 10;
decimalNumber = decimalNumber + remainder * j;
j = j * 2;
binaryString[c] = binaryString[c] / 10;
}
}
return decimalNumber;
}
int binaryToDecimalMain() {
int arraysize = 33;
char binaryString[arraysize];
scanf("%32s", binaryString);
printf("%d",binaryToDecimal(binaryString []);
return 0;
}
I not give you the algorithm because it's seems that you are learning how to program and it is important to you to learn to discover how to solve the problems that are given to you.But I can give you some hints:
use binaryString only to compare with '0' or '1'. Don't try to make any operations like '%' on it.
iterate on the binaryString character by character (no while inside for [this is only for this case, there some algorithm that is necessary to do something like this])
your logic to convert is on the right track
Also you should call your main function main.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
If i have length of 20 2d array
of length 5 integers represented as bits
int bitsval[6];
and the array looks like for example bitsval = {0,0,1,0,1,0}
and i want the decimal value so something like
(2^0 x 0) + ( 2^1 x 1) + (2^2 x 0)... and eventually return the final value as 10
can some one help write a function a function like this
This looks like a homework question, so I'll help, but not give you the code
What you need to do is have a 'total' variable, and a 'current bit worth' variable.
Start with the 'current bit worth' variable equal to 32 (2 ^ 5)
Then, have a loop going through the array, adding the bit worth on to the total if that bit is '1'
Each time you go to the next element in the array you need to half the 'current bit worth' value
[Edit]
OK - if it's not homework, try this:
total = 0;
bitvalue= 32;
for (i = 0; i < 6; i++) {
if (bitsval[i]) total += bitvalue;
bitvalue /= 2;
}
This should work I guess.
#include<math.h>
#include<stdio.h>
void main()
{
int a[]={1,0,0,1,0};
int sum=0;
for(int i=0; i<sizeof(a)/2; i++)
{
if(a[i]==1)
sum+=pow(2,(sizeof(a)/2)-i-1);
}
}
Without going into any kind of binary, and working of off of purely your explanation here is something that should work:
#include <stdio.h>
#include <math.h>
int main(){
int number[6] = {0,0,1,0,1,0}, result = 0;
for (int x = 5; x >= 0; --x){
result += (number[x] * (int) pow(2, 5-x));
}
printf("Final result: %d\n", result);
return 0;
}
You will off course have to massage it to fit