How to find min value of an n digit number? - c#

I have been able to achieve what I am looking for but just want to know whether there is an inbuilt method to do so?
I have a number say 2665. Now since this is a 4 digit, I need the minimum value of a 4 digit number which is 1000.
Similarly if the number is 255, the answer would be 100.
I tried this
int len = 2665.ToString().Length;
string str = string.Empty;
for (int index = 0; index < len; index++)
{
if (index == 0)
str += "1";
else
str += "0";
}
This gives correct result of 1000. But is there an inbuilt function for this?

You can use Pow and power 10 to length of string. For 1 it will give 1 for 2 it will give 10 etc.
var str = Math.Pow(10, len - 1).ToString();

You can also use constructor String(Char, Int32) of string to create the sequence of zeros you want.
string s = "1" + new string('0', str.Length-1);

Related

I'm trying to get sum of digits from a number, Where Is the Mistake? [duplicate]

This question already has answers here:
Sum of digits in C#
(18 answers)
Closed 1 year ago.
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for(int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber[i]);
}
Console.WriteLine(Sum);
it should show 3, But instead its showing 99.
What is actual mistake.
If you iterate the characters in a string, you'll get chars. The problem is that converting a char to an int with Convert.ToInt32(), will result in the ASCII Unicode UTF-16 value of that char.
The ASCII Unicode UTF-16 value of '1' = 49 and for '2' is 50 which sums 99.
You should make it a string first.
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for(int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber[i].ToString());
}
Console.WriteLine(Sum);
The problem is that Convert.ToInt32(sNumber[i]) is getting the numeric value of the character at position i, i.e. Convert.ToInt32('1') gives 49. Note that this value is a char and therefore Convert.ToInt32('1') returns the value of the UTF-16 character.
Why convert it to a string when plain mathematics will do what you want.
int number = 12;
int sum = 0;
while (number > 0){
sum += number % 10;
number /= 10; // Integer division
}
Console.WriteLine(sum);
Convert.ToNumber(char) returns code of character in ASCII. In your example 1 have code 49 and 2 have code 50. 49 + 50 results in 99
You need to use Sum = Sum + int.Parse(sNumber[i].ToString()) to get actual value of digit
no need to convert to string for this. Use simple mathematics.
int Number = 123;
int Sum = 0;
while (Number != 0)
{
Sum += (Number % 10);
Number = Number / 10;
}
System.Console.WriteLine(Sum);
Since it hasn't been posted, here's a simple one-liner using Linq:
int Sum = Number.ToString().Sum(x => (int)char.GetNumericValue(x));
Change it to the following:
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for (int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber.Substring(i,1));
}
Console.WriteLine(Sum);
Use Substring instead of []
Convert.ToInt32(char x) will give you the UTF16 value of the char.
See: https://learn.microsoft.com/de-de/dotnet/api/system.convert.toint32?view=net-5.0#System_Convert_ToInt32_System_Char_

count leading number of zeros in string

i need to count leading zeros in string.
this is what i found count leading zeros in integer
static int LeadingZeros(int value)
{
// Shift right unsigned to work with both positive and negative values
var uValue = (uint) value;
int leadingZeros = 0;
while(uValue != 0)
{
uValue = uValue >> 1;
leadingZeros++;
}
return (32 - leadingZeros);
}
but couldn't found counting leading zeros in string.
string xx = "000123";
above example have 000 so i want to get result count number as 3
how i can count zeros in string?
if anyone tip for me much appreciate
The Simplest approach is using LINQ :
var text = "000123";
var count = text.TakeWhile(c => c == '0').Count();
int can't have leading 0's, however I assume you just want to count leading zeros in a string.
Without getting fancy, just use a vanilla for loop:
var input = "0000234";
var count = 0;
for(var i = 0; i < input.Length && input[i] == '0'; i++)
count++;
Full Demo Here

How to divide number on separate digits to add values to each other

can you help me figure out how to calculate this way, for example I have some integer:
first I need condition
if (x < 10) to avoid asked calculation for single numbers
now if number contains more then 1 digit need to calculate it second way, for example, I got 134 how to separate it to calculate it this way 1 + 3 + 4 to attach this value 8 to variable.
So question is how to separate numbers
try
int num = 12345;
// holder temporarily holds the last digit of the number
int holder = 0;
int sum = 0;
while (num>0)
{
holder = num%10;
num = num/10;
sum += holder;
}
//sum would now hold the sum of each digit
This isn't C# in particular, but you can loop over your number then get it digit by digit.
// -- c
int num = 134;
int sum = 0;
while(num != 0) {
ones_digit = num % 10;
sum += ones_digit;
num = (num - ones_digit) / 10;
}
printf("sum: %d", sum);
On higher-level languages like javascript or python, accessing the digits can also be done by converting the integer to a string, then casting each char to an int type.
// -- javascript
var num = 134;
var digits = num.toString().split("").map(parseInt);
console.log(digits);

C# substring out of range

The problem I am having is that I need to be able to loop over a string, returning 5 characters after the position of the index, then starting 5 characters after.
However when there are less than 5 characters left an out of range error occurs, I thought it would just print the remaining characters of the string.
string string1 = "ghuitghtruighr";
for (int index = 0; index < string1.Length; index += 5)
{
string subString = string1.Substring(i, 5);
Console.WriteLine(subString);
}
How can I get it to print what's left of the string when whats remaining is less than 5?
You could use the LINQ .Skip(...) & .Take(...) operators like so:
for (int index = 0; index < string1.Length; index += 5)
{
string subString = new String(string1.Skip(index).Take(5).ToArray());
Console.WriteLine(subString);
}
That gives:
ghuit
ghtru
ighr
Replace line 3 of OP code with this:
string subString = string1.Substring(i, string1.Length - i < 5 ? string1.Length - i : 5);
You could Substring() from the index to the end of the string and then check whether the resulting substring contains more than 5 characters:
string string1 = "ghuitghtruighr";
for (int index = 0; index < string1.Length; index += 5)
{
string subString = string1.Substring(index);
if(subString.Length > 5)
subString = subString.Substring(0, 5);
Console.WriteLine(subString);
}
Don't do the above if you have many distinct strings of great length - strings are immutable so calling Substring() twice on every iteration results in an extra string on the heap every time - rather calculate the difference between Length and index like suggested by Xerillio

Having the nth char based on a variable not working as expected

So I have pow - a list containing numbers. I have to examine other numbers like this: Get all the digits and sum the numbers from pow having the same index as the certain digit.
So if I check number 4552 I need to get pow[4]+pow[5]+pow[5]+pow[2]. Because I'm a noob I try to convert the number to string, get the characters with loop and then convert back to int to get the index. So the code is as follows for getting the sums between 4550 and 4559:
for (int i = 4550; i < 4560; i++)
{
int sum = 0;
for (int j = 0; j < i.ToString().Length; j++)
{
sum += pows[Convert.ToInt32(i.ToString()[j])]; //here is the error - index was out of range
//do something with sum (like store it in another list)
}
}
So what is wrong with that?
EDIT: To avoid confusion... pow has 10 elements, from indexes 0-9.
SOLUTION: The issue with my code was that I got the character code not the digit itself, thanks Steve Lillis. Though the solution provided by Dmitry Bychenko is far more superior to my attempt. Thank you all.
What you're looking for is similar to a digital root:
Modulus (% in C#) is easier and faster than conversion to string:
public static int DigitalRootIndex(IList<int> list, int value) {
if (value < 0)
value = -value;
int result = 0;
// for value == 4552
// result == list[4] + list[5] + list[5] + list[2]
while (value > 0) {
int index = value % 10;
result += list[index];
value /= 10;
}
return result;
}
...
int test = DigitalRootIndex(pow, 4552);
This bit of code gets a single character such as '4' which is character code 59:
c = i.ToString()[j]
Then this bit of code turns that char into an integer. It doesn't parse it like you're expecting, so the result for '4' is 59, not 4:
Convert.ToInt32(c)
Do this instead:
int.Parse(c.ToString())
Something like this (quick and dirty try)?
int currentDigit;
int sum;
for (int i = 4550; i < 4560; i++)
{
sum = 0;
currentDigit = i;
while (currentDigit > 0)
{
if (pow.Count > (currentDigit % 10))
{
sum += pow[((currentDigit % 10))];
}
}
}
Note that lists have zero based index so when you do pow[1], you are actually accessing second element in the list. Is that what you want?

Categories