Write a function which given a string S returns the index (counting from 0) of character such that the substring on its left is a reversed susbstring on its right (or -1 if such an index does not exist).
For example, given a string
racecar
Function should return 3, because the substring on the left of the character e at index 3 is rac, and the one on the right is car.
get the length/2 and verify lengths first and then if the lengths are same then reverse the first half and compare with the second.
Example function:
private int TestMethod1(string str)
{
if (str.Length > 0)
{
if (str.Length % 2 != 0)
{
string strFront = string.Empty;
for (int i = (str.Length / 2) - 1; i >= 0; i--)
{
strFront += str.Substring(i, 1);
}
if (strFront.Equals(str.Substring((str.Length / 2) + 1)))
{
return str.Length / 2;
}
}
}
return -1;
}
Related
The rule is if value >= 500,000 it will be rounded up to 1,000,000, if the value < 500,000 it will be rounded down to 000,000
Here an example, if I have value like 4,843,820,00 it will be rounded up to 4,844,000,000
If I have value like 1,136,362,500 it will be rounded down to 1,136,000,000
If I have value like 1,500,000 will be rounded up to 2,000,000 & if I have like 1,450,000 it will be rounded down to 1,000,000
Here is what I tried
String kmbGenerator(number) {
if (number > 999 && number < 99999) {
int resulta = (number / 1000).round();
return "$resulta,000";
} else if (number > 99999 && number < 999999) {
int resulta = (number / 1000).round();
return '${resulta.toStringAsFixed(0)},000';
} else if (number > 999999 && number < 999999999) {
int resulta = (number / 1000000).round();
return "$resulta,000,000";
} else if (number > 999999999) {
int resulta = (number / 1000000000).round();
return "$resulta,000,000,000";
} else {
return number.toString();
}
}
Divide by one million, round, then multiply by one million:
int roundMillions(int value) {
return (value / 1e6).round() * 1000000;
}
main() {
void test(int value) {
print('rounded $value to ${roundMillions(value)}');
}
test(4843820000);
test(1136362500);
test(1500000);
test(1450000);
}
Output:
rounded 4843820000 to 4844000000
rounded 1136362500 to 1136000000
rounded 1500000 to 2000000
rounded 1450000 to 1000000
Before you format round it using num.round() for example if you want to round to millions :
double n = 29971800;
double roundTo = 1000000; //million
print((n/roundTo).round()); //prints 30
you can either multiply it by million and format it or just convert to String and add ',000,000'
Is there a better way to calculate a moving sum of a list?
List<double?> rollingSum({int window = 3, List data = const []}) {
List<double?> sum = [];
int i = 0;
int maxLength = data.length - window + 1;
while (i < maxLength) {
List tmpData = data.getRange(i, i + window).toList();
double tmpSum = tmpData.reduce((a, b) => a + b);
sum.add(tmpSum);
i++;
}
// filling the first n values with null
i = 0;
while (i < window - 1) {
sum.insert(0, null);
i++;
}
return sum;
}
Well, the code is already clean for what you need. Maybe just some improvements like:
Use a for loop
You can use the method sublist which creates a "view" of a list, which is more efficient
To insert some values in the left/right of a list, there is a specific Dart method called padLeft, where you specify the lenght of the list which you want it to become (first parameter), then the value you want to use to fill it (second parameter). For example, if you have an array of N elements, and you want to fill it with X "null"s to the left, use padLeft(N+X, null).
List<double?> rollingSum({int window = 3, List data = const []}) {
List<double?> sum = [];
for (int i = 0; i < data.length - window + 1; i++) {
List tmpData = data.sublist(i, i + window);
double tmpSum = tmpData.reduce((a, b) => a + b);
sum.add(tmpSum);
}
sum.padLeft(window - 1, null);
return sum;
}
if I understand your problem correctly you can just calculate the window one time and in one loop you can for each iteration you can add the current element to the sum and subtract i - (window - 1)
so for an input like this
data = [1,2,3,4,5,6]
window = 3
the below code will result in [6,9,12,15]
int sum = 0;
List<double> res = [];
for (int i = 0;i<data.length;i++) {
sum += data[i];
if (i < window - 1) {
continue;
}
res.add(sum);
sum -= data[i - (window - 1)]; // remove element that got out of the window size
}
this way you won't have to use getRange nor sublist nor reduce as all of those are expensive functions in terms of time and space complexity
I want to solve leetcode 172nd question using dart. Take the factorial of a given number and find how many zeros there are at the end.
I done until now
void main() {
print(factorial(5));
}
factorial(int input) {
int factorial = 1;
var answer = 0;
for (int i = 1; i <= input; i++) {
factorial *= i;
}
while (factorial > 10 && factorial.toString().split('').last == "0") {
factorial = (factorial / 10)
answer++;
}
return answer;
}
but when i divide factorial by 10 it not allowed. and if assing at the begining like
double factorial=1;
this time the number is 120.0 and then zero is more. Can anyone help on this, thanks
You can use method for double to int;
double a = 8.5;
print(a.toInt()) // 8
Answer:
while (factorial > 10 && factorial.toString().split('').last == "0") {
factorial = (factorial / 10).toInt(); // Add toInt()
answer++;
}
To convert a double to int, just use:
double x = 1.256;
print(x.toInt()); //this will print 1
I am not sure what you are asking in this question other than this.
Check the accepted answer to this Question: How to do Integer division in Dart?
Integer division in Dart has its own operator: ~/ as in
print(16 ~/ 3);
I'm looking for a clean and efficient way to validate an Israeli ID number.
It's basically an implementation of the Luhn algorithm on a 9 digits number.
Note:
This question is here for the community because it wasn't on stack overflow yet.
You can add answers in different coding languages.
Here's an efficient way to implement it in C# (link):
public static bool IsValidIsraeliID(string israeliID)
{
if (israeliID.Length != 9)
return false;
long sum = 0;
for (int i = 0; i < israeliID.Length; i++)
{
var digit = israeliID[israeliID.Length - 1 - i] - '0';
sum += (i % 2 != 0) ? GetDouble(digit) : digit;
}
return sum % 10 == 0;
int GetDouble(long i)
{
switch (i)
{
case 0: return 0;
case 1: return 2;
case 2: return 4;
case 3: return 6;
case 4: return 8;
case 5: return 1;
case 6: return 3;
case 7: return 5;
case 8: return 7;
case 9: return 9;
default: return 0;
}
}
}
JS example code like it appears in Wikipedia:
https://he.wikipedia.org/wiki/ספרת_ביקורת
function IDValidator(id)
{
if (id.length !== 9 || isNaN(id)) { // Make sure ID is formatted properly
return false;
}
let sum = 0, incNum;
for (let i = 0; i < id.length; i++) {
incNum = Number(id[i]) * ((i % 2) + 1); // Multiply number by 1 or 2
sum += (incNum > 9) ? incNum - 9 : incNum; // Sum the digits up and add to total
}
return (sum % 10 === 0);
}
How to get a number converted into something like this: 12K, 1.5M, 4.2B from a normal number like: 134900.
This is a minimalist function, of course you'll have to add validation code to verify if the number is valid before executing the function. Otherwise Enjoy ...
void main() {
double num = 1250;
var myNumber = k_m_b_generator(num);
print(myNumber);
}
String k_m_b_generator(num) {
if (num > 999 && num < 99999) {
return "${(num / 1000).toStringAsFixed(1)} K";
} else if (num > 99999 && num < 999999) {
return "${(num / 1000).toStringAsFixed(0)} K";
} else if (num > 999999 && num < 999999999) {
return "${(num / 1000000).toStringAsFixed(1)} M";
} else if (num > 999999999) {
return "${(num / 1000000000).toStringAsFixed(1)} B";
} else {
return num.toString();
}
}
You can use flutter's NumberFormat class with the compact function.
formatNumber(dynamic myNumber) {
// Convert number into a string if it was not a string previously
String stringNumber = myNumber.toString();
// Convert number into double to be formatted.
// Default to zero if unable to do so
double doubleNumber = double.tryParse(stringNumber) ?? 0;
// Set number format to use
NumberFormat numberFormat = new NumberFormat.compact();
return numberFormat.format(doubleNumber);
}
The answer is not entirely correct. If you test it, you will see what i meant. Base on the answer above, I created this solution:
String numberFormat(int n) {
String num = n.toString();
int len = num.length;
if (n >= 1000 && n < 1000000) {
return num.substring(0, len - 3) + '.' + num.substring(len - 3, 1 + (len - 3)) + 'k';
} else if (n >= 1000000 && n < 1000000000) {
return num.substring(0, len - 6) + '.' + num.substring(len - 6, 1 + (len - 6)) + 'm';
} else if (n > 1000000000) {
return num.substring(0, len - 9) + '.' + num.substring(len - 9, 1 + (len - 9)) + 'b';
} else {
return num.toString();
}
}